XDocument在XML节点

时间:2018-03-27 16:16:27

标签: c# xml

我有这个XML

<?xml version="1.0" encoding="utf-8" standalone="no"?>
<S:Envelope xmlns:S="http://schemas.xmlsoap.org/soap/envelope/">
  <S:Header>
    <wss:Security xmlns:wss="http://schemas.xmlsoap.org/ws/2002/12/secext">
      <wss:UsernameToken>
        <wss:Username>username</wss:Username>
        <wss:Password>password</wss:Password>
        <wss:Nonce></wss:Nonce>
        <wss:Created></wss:Created>
      </wss:UsernameToken>
    </wss:Security>
  </S:Header>
  <S:Body>
      <TaxRegistrationNumber>213213123</TaxRegistrationNumber>
      <CompanyName>sadsadasd</CompanyName>
  </S:Body>
</S:Envelope>


我想访问<wss:Username>的值并在<wss:Nonce>节点中设置一个值。

我已经尝试了3种方法来获取C#项目<wss:Username>的值:

第一:
XDocument xmlFile = XDocument.Load(xmlpathfile);
XmlNamespaceManager ns = new XmlNamespaceManager(new NameTable());
ns.AddNamespace("wss", "http://schemas.xmlsoap.org/ws/2002/12/secext/");
XElement UserFinanc = xmlFile.XPathSelectElement("wss:Security/wss:UsernameToken/wss:Username", ns);

第二:
XDocument xmlFile = XDocument.Load(xmlpathfile);
XmlNamespaceManager ns = new XmlNamespaceManager(new NameTable());
var element = xmlFile.Descendants(wss + "Security").Descendants(wss + "UsernameToken").Where(x => x.Descendants(wss + "Username").Any(y => y.Value != "")).First().Element(wss + "UsernameToken");
if (element != null)
MessageBox.Show(element.Element(wss + "Username").Value).Value);

第三:
string grandChild = (string) (from el in xmlFile.Descendants(wss + "Username") select el).First();
MsgBox.Show(grandChild);

我总是有类似的错误,例如&#39;序列不包含任何元素&#39;

1 个答案:

答案 0 :(得分:0)

你的第一次尝试几乎是正确的。缺少一些东西:

  1. 代码中定义的命名空间必须与完全匹配。在您的情况下,代码中的命名空间有一个额外的尾部斜杠。它应该是http://schemas.xmlsoap.org/ws/2002/12/secext
  2. XPath表达式应为//wss:Security/wss:UsernameToken/wss:Username。领先的斜杠基本上意味着&#34;在任何地方寻找这个节点&#34;。或者,您可以写出以<S:Envelope>开头的整个路径。您还需要在代码中添加soap envelope名称空间。