LINQ to XML. How to get some string?

2020-04-20 11:31发布

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!

2条回答
叼着烟拽天下
2楼-- · 2020-04-20 12:07

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;
查看更多
Evening l夕情丶
3楼-- · 2020-04-20 12:32

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(); 
查看更多
登录 后发表回答