use*_*385 2 c# xml parsing linq-to-xml
我在使用具有多个名称空间的根节点解析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>
Run Code Online (Sandbox Code Playgroud)
我试过了:
XDocument webXMLResource = XDocument.Load(@"../../../../Web.xml");
IEnumerable<XElement> values = webXMLResource.Descendants("object");
Run Code Online (Sandbox Code Playgroud)
没有返回任何结果.
Ser*_*kiy 10
命名空间的另一个技巧 - 您可以使用XElement.GetDefaultNamespace()来获取根元素的默认命名空间.然后使用此默认命名空间进行查询:
var xdoc = XDocument.Load(path_to_xml);
var ns = xdoc.Root.GetDefaultNamespace();
var objects = xdoc.Descendants(ns + "object");
Run Code Online (Sandbox Code Playgroud)
当您Decendants使用XName参数调用XName's NameSpace(碰巧为空)时Name,除了LocalName. 所以你可以查询LocalName
p.Descendants().Where(p=>p.Name.LocalName == "object")
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
13792 次 |
| 最近记录: |