如何获取 XML 节点的值?

How to get value of an XML node?

我一直无法从这个 XML 文档中提取 SourcePartyName

<ns0:Visit xmlns:ns0="http://Co.Burgers.Ues">
<ns0:SourcePartyName>NDHARY</ns0:SourcePartyName>
</ns0:Visit>

使用 Scott 的 solution,我已经能够提取命名空间信息;然而,经过数十次尝试 XDocument / XElement 后,我无法获得所需的 NDHARY 值。

尝试包括:

xdoc.Descendants(ns + "SourcePartyName").FirstOrDefault()?.Value;

xdoc.Element(ns + "SourcePartyName").Value;

如何从 XDocument 中获取节点的值?

使用 XDocument 时,您必须通过其 Root 属性.

String xml = @"
    <ns0:Visit xmlns:ns0=""http://Co.Burgers.Ues"">
        <ns0:SourcePartyName>NDHARY</ns0:SourcePartyName>
    </ns0:Visit>
    ";
XDocument xdoc = XDocument.Parse(xml);
XNamespace ns = "http://Co.Burgers.Ues";
String sourcePartyName = (String)xdoc.Root.Element(ns + "SourcePartyName");