XDocument 读取具有命名空间的根元素的 XML 文件
本文关键字:元素 XML 文件 命名空间 读取 XDocument | 更新日期: 2023-09-27 18:33:41
我在解析根节点具有多个命名空间的 XML 文件时遇到一些问题。我想获取类型字符串包含"用户控件库"的节点"对象"列表:
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");
不返回任何结果。
命名空间的另一个技巧 - 您可以使用 XElement.GetDefaultNamespace() 获取根元素的默认命名空间。然后使用此默认命名空间进行查询:
var xdoc = XDocument.Load(path_to_xml);
var ns = xdoc.Root.GetDefaultNamespace();
var objects = xdoc.Descendants(ns + "object");
当你用XName
参数调用Decendants
时,除了LocalName
之外,XName
的NameSpace
(碰巧是空的)实际上还被合并到Name
中。因此,您只需通过LocalName
即可查询
p.Descendants().Where(p=>p.Name.LocalName == "object")
尝试使用命名空间:
var ns = new XNamespace("http://www.springframework.net");
IEnumerable<XElement> values = webXMLResource.Descendants(ns + "object");
如果您使用的是死者,则必须添加如下所示的名称空间
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;
希望它对你有用