简体   繁体   中英

Get attribute value from a tag Linq to XML

I'm using Linq to get some xml values, but this time I want to get the content of "href" attribute from tag, which is like this:

<link rel="alternate" type="text/html" href="Value I want to retrieve"/>
<link rel="alternate" type="text/html" href="Another Value want to retrieve"/>

any clues how to do that?

I am able to get values of tags

<title>1st title</title>
<title>2nd title</title>

this way:

IEnumerable<XElement> item = document.Descendants(xmlns + "title");
// to print use: item.ElementAt<XElement>(0).Value;

But I failed to retrieve a value from the href attribute, any help is appreciated.

How about this:

IEnumerable<string> links = document.Descendants("link")
    .Select(element => element.Attribute("href").Value);

... or just:

var links = document.Descendants("link")
    .Attributes("href")
    .Select(element => element.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