简体   繁体   中英

How to get the value of an XML attribute?

I have a XML file:

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

How could I use LINQ to get the <type> attribute of the <title> element, ie "p1", "p2" and "p3"?

Use XDocument.Load or XDocument.Parse to load the XML data into an XDocument . Then, using LINQ, you can get the type for each <title> element under the document root as follows:

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);
}

Output:

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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