Parsing XML containing namespace declarations can be challenging using LINQ to XML.
Consider the following XML code:
<code class="language-xml"><Response xmlns="http://myvalue.com"><Result xmlns:a="http://schemas.datacontract.org/2004/07/My.Namespace" xmlns:i="http://www.w3.org/2001/XMLSchema-instance"><a:TheBool>true</a:TheBool><a:TheId>1</a:TheId></Result></Response></code>
To parse this XML we can use the following code:
<code class="language-csharp">XDocument xmlElements = XDocument.Parse(theXml); XNamespace ns = "http://myvalue.com"; XNamespace nsa = "http://schemas.datacontract.org/2004/07/My.Namespace"; var elements = from data in xmlElements.Descendants(ns + "Result") select new { TheBool = (bool)data.Element(nsa + "TheBool"), TheId = (int)data.Element(nsa + "TheId"), };</code>
Note the use of Descendants
within ns
and Elements
within nsa
. These namespaces enable LINQ to XML methods to identify the correct elements.
The above is the detailed content of How Can I Effectively Parse XML with Namespaces Using LINQ to XML?. For more information, please follow other related articles on the PHP Chinese website!