C# Linq to XML query

后端 未结 3 1883
旧巷少年郎
旧巷少年郎 2021-01-21 16:20

  
    
      
        
        
        <         


        
相关标签:
3条回答
  • 2021-01-21 16:55
    var result = xdoc.Descendants("World")
                     .Descendants("Animals")
                     .Descendants("Tab")
                     .Elements("Dogs")
                     .Where(n => n.Attribute("id").Value == "1");
    

    Output:

    <Dogs id="1">
      <Dog1></Dog1>
      <Dog2></Dog2>
      <Dog3></Dog3>
    </Dogs>
    
    0 讨论(0)
  • 2021-01-21 16:59

    Or use XPath:

    xml.XPathSelectElements("/World/Animals/Tab/Dogs[@id=1]")
    

    or

    xml.XPathSelectElements("//Dogs[@id=1]")

    which would find all Dogs wherever they occurred.

    0 讨论(0)
  • 2021-01-21 16:59

    From your sample data I think you want

    //from e in xml.Descendants("Animals").Descendants("Tab").Elements("Dogs")
    from e in xml.Descendants("Animals").Elements("Tab").Descendants("Dogs")
    

    And in the same line, Descendants("Animals") could be Elements("Animals") if you want to enforce the structure.

    For the rest your query looks OK.

    0 讨论(0)
提交回复
热议问题