3

我在解析具有多个命名空间的根节点的 XML 文件时遇到了一些问题。我想得到一个节点 'object' 的列表,其类型字符串包含 'UserControlLibrary':
XML 文件:

<?xml version="1.0" encoding="utf-8" ?>
<objects xmlns="http://www.springframework.net"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.net 
http://www.springframework.net/xsd/spring-objects.xsd">

<!-- master pages -->
<object type="RLN.Site, RLN">
    <property name="ContainerBLL" ref="ContainerBLL"></property>
    <property name="UserBLL" ref="UserBLL"></property>
    <property name="TestsBLL" ref="TestsBLL"></property>
<property name="GuidBLL" ref="GuidBLL"></property>
</object>

<object type="RLN.UserControlLibrary.topleveladmin, RLN.UserControlLibrary">
    <property name="ContainerBLL" ref="ContainerBLL"></property>
    <property name="UserBLL" ref="UserBLL"></property>
    <property name="GuidBLL" ref="GuidBLL"></property>
</object>



<object type="RLN.UserControlLibrary.topleveladminfloat, RLN.UserControlLibrary">
    <property name="ContainerBLL" ref="ContainerBLL"></property>
    <property name="UserBLL" ref="UserBLL"></property>
</object>
</objects>

我努力了:

  XDocument webXMLResource = XDocument.Load(@"../../../../Web.xml");
  IEnumerable<XElement> values = webXMLResource.Descendants("object");

没有返回结果。

4

4 回答 4

12

命名空间的另一个技巧 - 您可以使用XElement.GetDefaultNamespace()来获取根元素的默认命名空间。然后使用此默认命名空间进行查询:

var xdoc = XDocument.Load(path_to_xml);
var ns = xdoc.Root.GetDefaultNamespace();
var objects = xdoc.Descendants(ns + "object");
于 2013-10-02T17:17:23.947 回答
5

当您Decendants使用XName参数调用时XName's NameSpace(恰好是空的)实际上被合并到Name除了LocalName. 所以你可以通过查询LocalName

p.Descendants().Where(p=>p.Name.LocalName == "object")
于 2013-10-02T17:04:32.237 回答
2

尝试使用命名空间:

var ns = new XNamespace("http://www.springframework.net");
IEnumerable<XElement> values = webXMLResource.Descendants(ns + "object");
于 2013-10-02T17:13:50.753 回答
0

如果您使用的是死者,则必须添加如下命名空间

 XDocument webXMLResource = XDocument.Load(@"../../../../Web.xml");
 XNamespace _XNamesapce = XNamespace.Get("http://www.w3.org/2001/XMLSchema-instance");
 IEnumerable<XElement> values = from ele in webXMLResource .Descendants(_XNamesapce + "object")
                                select ele;

希望它对你有用

于 2013-10-03T12:16:30.003 回答