LINQ to XML. How to get some string?

后端 未结 2 635
旧巷少年郎
旧巷少年郎 2021-01-25 18:29

I have xml:



  
    Ray
    Other

        
相关标签:
2条回答
  • 2021-01-25 19:33

    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;
    
    0 讨论(0)
  • 2021-01-25 19:34

    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(); 
    
    0 讨论(0)
提交回复
热议问题