使用XDocument读取具有命名空间的根元素的XML文件

3

我有些困难在解析具有多个命名空间的根节点的XML文件中。我想要获取一个类型为字符串且包含“UserControlLibrary”的“object”节点列表:
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个回答

13

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

var xdoc = XDocument.Load(path_to_xml);
var ns = xdoc.Root.GetDefaultNamespace();
var objects = xdoc.Descendants(ns + "object");

当中间节点承载额外的命名空间时,它无法工作。我错了吗? - Alireza
@Alireza 是的,完全正确。在这种情况下,对象将不会位于根元素的默认命名空间中。 - Sergey Berezovskiy

5
当您使用XName参数调用Decendants时,XNameNameSpace(空值)被实际上并入到Name中,除了LocalName。因此,您可以仅通过LocalName进行查询。
p.Descendants().Where(p=>p.Name.LocalName == "object")

正是我所需要的 :) - Shrikey

2

尝试使用命名空间:

var ns = new XNamespace("http://www.springframework.net");
IEnumerable<XElement> values = webXMLResource.Descendants(ns + "object");

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;

希望它能为你工作。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接