简体   繁体   中英

issue to get specific XML element value using C#

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.

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>

Use System.Xml.XmlTextReader class,

System.Xml.XmlTextReader xr = new XmlTextReader(@"file.xml");
        while (xr.Read())
        {
            if (xr.LocalName == "name" && xr.Prefix == "a")
            {
                xr.Read();
                Console.WriteLine(xr.Value);
            }
        }

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);

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);

XPath is the direct way to get at bits of an XML document in 2.0

XmlDocument xml = new XmlDocument();
xml.Load("file.xml") 
XmlNamespaceManager manager = new XmlNamespaceManager(xml.NameTable);
manager.AddNamespace("a", "http://schemas.datacontract.org/2004/07/FOO.WCF");
string name = xml.SelectSingleNode("//a:name", manager).InnerText; 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM