1

所以我试图解析一个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);
}

除非我从 xml 文件中删除 xmlns="http://foo.co.uk/nan" ,否则不会将任何内容写入控制台,之后,我会得到一个属性名称和值的列表,正如我所期望的那样,并且我需要!

编辑:格式化。

4

3 回答 3

3

您必须在代码中使用相同的命名空间:

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 使用来说是纯本地的,名称实际上总是命名空间 + 本地名称,因此您必须始终指定命名空间。

于 2010-03-11T14:31:21.430 回答
2

您对Descendants的调用是在无命名空间中查询名为“att1”的元素。

如果您打电话Descendants("{http://foo.co.uk/nan}att1"),您将选择命名空间元素,而不是非命名空间元素。

您可以在任何或没有命名空间中选择名为“att1”的元素,如下所示:

var query = from c in xDoc.Descendants() where c.Name.LocalName == "att1" select c.Attributes;
于 2010-03-11T14:39:38.443 回答
1

您需要在Descendants调用中指定命名空间,如下所示:

XNamespace ns = "http://foo.co.uk/nan";
foreach (XAttribute a in xDoc.Descendants(ns + "att1"))
{
    Console.WriteLine("{0}, {1}",a.Name,a.Value);
}
于 2010-03-11T14:31:38.760 回答