To get the specific value of an XML element using C #

Suppose I have the following XML document, how to get the value of an element for the name a: (in my example, the value is Saturday 100)? My confusion is how to deal with namespace. 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> 
+2
source share
3 answers

This is easier if you use LINQ to XML classes. Otherwise, namespaces are really 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); 

Change Usage 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); 
+4
source

Use the 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); } } 
+5
source

XPath is a direct way to get the bits of an XML document in version 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; 
+3
source

Source: https://habr.com/ru/post/915279/


All Articles