XDocument get XML element by the value of its name attribute

前端 未结 2 1671
暖寄归人
暖寄归人 2021-01-01 16:20

I have an XML result like this


  
    0
    

        
相关标签:
2条回答
  • 2021-01-01 16:40

    Does this solve your problem:

    var test = from c in xml.Descendants("doc")
               select new 
               {
                   firstname = c.Elements("str").First(element => element.Attribute("name").Value == "ContaFirstname"),
                   surnmane = c.Elements("str").First(element => element.Attribute("name").Value == "ContaSurname")
               }; 
    

    or, if you want the values (instead of XElement:

    var test = from c in xml.Descendants("doc")
               select new 
               {
                   firstname = c.Elements("str").First(element => element.Attribute("name").Value == "ContaFirstname").Value,
                   surnmane = c.Elements("str").First(element => element.Attribute("name").Value == "ContaSurname").Value
               }; 
    
    0 讨论(0)
  • 2021-01-01 16:48

    You don't want to access the elements by name as most people would interpret that statement. You want to access the elements by the value of their name attribute:

    firstname = (string) c.Elements("str")
                          .First(x => x.Attribute("name").Value == "ContaFirstname");
    //etc
    

    You may well want to abstract that into a separate method, as it's going to be a pain to do it multiple times. For example:

    public static XElement ElementByNameAttribute(this XContainer container,
                                                  string name)
    {
        return container.Elements("str")
                        .First(x => x.Attribute("name").Value == name);
    }
    

    Then:

    var test = from c in xml.Descendants("doc")
               select new 
               { 
                   firstname = c.ElementByNameAttribute("ContaFirstname").Value,
                   surnmane = c.ElementByNameAttribute("ContaSurname").Value
               }; 
    

    If you have any chance to give your document a more sensible structure, that would be preferable...

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