【问题标题】:XDocument Reading XML file with Root element having namespacesXDocument 读取具有名称空间的根元素的 XML 文件
【发布时间】:2026-01-14 13:15:01
【问题描述】:

我在解析具有多个命名空间的根节点的 XML 文件时遇到了一些问题。我想获取类型字符串包含“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");

没有返回结果。

【问题讨论】:

    标签: c# xml parsing linq-to-xml


    【解决方案1】:

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

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

    【讨论】:

    • 中间节点承载额外命名空间时不起作用。我错了吗?
    • @Alireza 是的,完全正确。在这种情况下,对象将不在根元素的默认命名空间中
    【解决方案2】:

    当您使用XName 参数调用Decendants 时,XName'sNameSpace(恰好是空的)实际上被合并到NameLocalName 中。所以你可以通过LocalName查询

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

    【讨论】:

    • 正是我想要的:)
    【解决方案3】:

    尝试使用命名空间:

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

    【讨论】:

      【解决方案4】:

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

       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;
      

      希望对你有用

      【讨论】: