C# XDocument读取根元素具有名称空间的XML文件

C# XDocument读取根元素具有名称空间的XML文件,c#,xml,parsing,linq-to-xml,C#,Xml,Parsing,Linq To Xml,我在解析根节点具有多个名称空间的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:schemaLocati

我在解析根节点具有多个名称空间的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");
XDocument webXMLResource=XDocument.Load(@../../../../../Web.xml”);
IEnumerable values=webXMLResource.subjects(“对象”);

没有返回任何结果

当您使用
XName
参数调用
decentants
时,
XName
命名空间
(碰巧是空的)除了
本地名称
之外,实际上还被合并到
名称中。因此,您可以通过
LocalName

p.Descendants().Where(p=>p.Name.LocalName == "object")

尝试使用名称空间:

var ns = new XNamespace("http://www.springframework.net");
IEnumerable<XElement> values = webXMLResource.Descendants(ns + "object");
var ns=新的XNamespace(“http://www.springframework.net");
IEnumerable values=webXMLResource.subjects(ns+“对象”);

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

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

如果您使用decedent,则必须添加名称空间,如下所示

 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;
XDocument webXMLResource=XDocument.Load(@../../../../../Web.xml”);
XNamespace XNamesapce=XNamespace.Get(“http://www.w3.org/2001/XMLSchema-instance");
IEnumerable values=来自webXMLResource.substands(XNamesapce+“对象”)中的元素
选择ele;

希望它能为您工作

当中间节点带有附加名称空间时,它不起作用。“我错了吗?”阿利雷扎是的,没错。在这种情况下,对象将不在根元素的默认名称空间中,正如我所寻找的:)