我在解析根节点具有多个命名空间的 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");
没有返回结果。
最佳答案
命名空间的另一个技巧 - 你可以使用 XElement.GetDefaultNamespace()获取根元素的默认命名空间。然后使用这个默认命名空间进行查询:
var xdoc = XDocument.Load(path_to_xml);
var ns = xdoc.Root.GetDefaultNamespace();
var objects = xdoc.Descendants(ns + "object");
关于c# - XDocument 使用具有 namespace 的 Root 元素读取 XML 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19142606/