在LINQ to XML中处理XML命名空间
处理包含命名空间的XML数据时,正确处理命名空间对于检索和操作所需元素至关重要。以下是如何使用LINQ to XML遍历包含命名空间的XML:
提供的示例代码:
<code class="language-csharp">string theXml = @"<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>"; XDocument xmlElements = XDocument.Parse(theXml); var elements = from data in xmlElements.Descendants("Result") select new { TheBool = (bool)data.Element("TheBool"), TheId = (int)data.Element("TheId"), };</code>
当XML字符串中使用命名空间时,此代码无法正确解析XML,导致出现空值。为了解决这个问题,我们需要在LINQ查询中显式指定XML命名空间。
在LINQ查询中定义XML命名空间,可以使用XNamespace
对象。此对象允许您创建具有适当命名空间前缀和URI的XName
实例。
以下是更正后的代码:
<code class="language-csharp">string theXml = @"<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>"; 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>
在更正后的代码中,我们首先使用命名空间URI声明XNamespace
对象ns
和nsa
。然后,在Descendants
和Element
查询中,我们指定带有命名空间前缀的XName
。通过这种方式,LINQ to XML可以正确识别和访问指定命名空间中的元素。
以上是如何使用 LINQ to XML 正确解析带有命名空间的 XML?的详细内容。更多信息请关注PHP中文网其他相关文章!