问题用C#来获得特定的XML元素的值元素、问题、XML

2023-09-03 23:29:04 作者:忆春风人不如故

假设我有以下的XML文档,如何获得一个元素值:名称(在我的示例中,值是周六100)?我的困惑是如何处理的名字空间。谢谢你。

Suppose I have the following XML document, how to get the element value for a:name (in my sample, the value is Saturday 100)? My confusion is how to deal with the name space. Thanks.

我使用C#和VSTS 2008。

I am using C# and VSTS 2008.

<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/">
  <s:Body>
    <PollResponse xmlns="http://tempuri.org/">
       <PollResult xmlns:a="http://schemas.datacontract.org/2004/07/FOO.WCF" xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
          <a:name>Saturday 100</a:name>
       </PollResult>
    </PollResponse>
  </s:Body>
</s:Envelope>

在此先感谢, 乔治

thanks in advance, George

推荐答案

这是更容易,如果您使用的LINQ to XML类。否则,命名空间真的是烦人。

It's easier if you use the LINQ to XML classes. Otherwise namespaces really are annoying.

XNamespace ns = "http://schemas.datacontract.org/2004/07/FOO.WCF";
var doc = XDocument.Load("C:\\test.xml"); 
Console.Write(doc.Descendants(ns + "name").First().Value);

编辑。使用2.0

Edit. Using 2.0

XmlDocument doc = new XmlDocument();
doc.Load("C:\\test.xml");
XmlNamespaceManager ns = new XmlNamespaceManager(doc.NameTable);
ns.AddNamespace("a", "http://schemas.datacontract.org/2004/07/FOO.WCF");
Console.Write(doc.SelectSingleNode("//a:name", ns).InnerText);