繁体   English   中英

如何获取XML属性的值?

[英]How to get the value of an XML attribute?

我有一个XML文件:

<SourceMessage xmlns="test.test">
  <updated>2011</updated>
  <title type="p1"/>
  <title type="p2"/>
  <title type="p3"/>
  <entry>
  </entry>
</SourceMessage> 

我如何使用LINQ获得<title>元素的<type>属性,即“ p1”,“ p2”和“ p3”?

使用XDocument.LoadXDocument.Parse将XML数据加载到XDocument中 然后,使用LINQ,可以获得文档根目录下每个<title>元素的类型,如下所示:

XNamespace test = "test.test";

XDocument doc = XDocument.Load(file);
// - or -
XDocument doc = XDocument.Parse("<SourceMessage ...");

IEnumerable<string> query = from title in doc.Root.Elements(test + "title")
                            select (string)title.Attribute("type");

foreach (string item in query)
{
    Console.WriteLine(item);
}

输出:

p1
p2
p3
var xElement XElement.Parse(xmlString);
var result = xElement.Descendants("title")
                     .Select(e => e.Attribute("type").Value);
XDocument xml = XDocument.Parse (@"<SourceMessage xmlns="test.test">
<updated>2011</updated>
  <title type="p1"/>
  <title type="p2"/>
  <title type="p3"/>
  <entry>
  </entry>
</SourceMessage>");

foreach (var t in xml.Root.Descendants("title"))
    Console.Write(t.Attribute("type").Value);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM