I have xml:
<?xml version="1.0" encoding="utf-8" ?>
<books>
<book>
<author>Ray</author>
<album>Other</album>
<cover size="large">LargeCover</cover>
<cover size="mini">MiniCover</cover>
</book>
</books>
How to get string "MiniCover"?
I wrote the code, but it does not work — string is empty;
string testLink = (@"Text.xml");
XDocument xml = XDocument.Load(testLink);
string cv = String.Empty;
var c = from cover in xml.Elements("book")
where (string)cover.Attribute("size").Value == "mini"
select cover.Value;
foreach (var item in c)
{
cv += item.ToString();
}
MessageBox.Show(cv);
Thanks!
Xpath can simplify your code
var covers = xDoc.XPathSelectElements("//cover[@size='mini']").ToList();
to get the inner text
var covers = xDoc.XPathSelectElements("//cover[@size='mini']")
.Select(x => x.Value)
.ToList();
When using Elements()
you have to specify the structure more precisely.
In your code, cover
is a <book>
element. But size
is an attribute of <cover>
.
var c = from cover in xml.Elements("book")
where (string)cover.Attribute("size").Value == "mini"
select cover.Value;
This ought to work:
var c = from cover in xml.Elements("book")
.Elements("cover")
where (string)cover.Attribute("size").Value == "mini"
select cover.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.