为什么秋天的XElement与解析了xmlns XML文件时结束了吗?
-
19-09-2019 - |
题
所以我试图解析XML文件:
<?xml version="1.0" encoding="utf-8" ?>
<Root>
<att1 name="bob" age="unspecified" xmlns="http://foo.co.uk/nan">
</att1>
</Root>
使用以下代码:
XElement xDoc= XElement.Load(filename);
var query = from c in xDoc.Descendants("att1").Attributes() select c;
foreach (XAttribute a in query)
{
Console.WriteLine("{0}, {1}",a.Name,a.Value);
}
没有被写入到控制台,除非我删除的xmlns从XML文件=“http://foo.co.uk/nan”,在这之后,我得到的属性名称,并正如人们所期望的值的列表,因为我需要!
编辑:格式化
解决方案
您必须使用相同的命名空间中的代码:
XElement xDoc= XElement.Load(filename);
XNamespace ns = "http://foo.co.uk/nan";
var query = from c in xDoc.Descendants(ns + "att1").Attributes() select c;
foreach (XAttribute a in query)
{
Console.WriteLine("{0}, {1}",a.Name,a.Value);
}
属性不拿起默认(xmlns=....
)命名空间,所以你不需要限定它们。命名空间标签(xmln:tags=....
)是纯粹的本地文档或API的使用,该名称是真正的命名空间+总是那么你必须始终指定命名空间的本地名称。
其他提示
您呼叫后代是查询命名的元素“ ATT1" 没有命名空间。
如果你叫Descendants("{http://foo.co.uk/nan}att1")
你会选择命名空间的元素,但不是非名称空间的元素。
您可以在任何选择名为“ATT1”元素或没有命名空间是这样的:
var query = from c in xDoc.Descendants() where c.Name.LocalName == "att1" select c.Attributes;
您需要在Descendants
调用指定命名空间,这样的:
XNamespace ns = "http://foo.co.uk/nan";
foreach (XAttribute a in xDoc.Descendants(ns + "att1"))
{
Console.WriteLine("{0}, {1}",a.Name,a.Value);
}
不隶属于 StackOverflow