XDocument to List of object

后端 未结 1 1602
小蘑菇
小蘑菇 2020-12-21 21:55

The content of an XDocument is the XML below.

I\'d like to get a List(), see at the end of this message.


  
         


        
相关标签:
1条回答
  • 2020-12-21 22:54

    Sure - so you need something like this:

    var query = from datas in doc.Root.Elements("myDatas")
                let code = (string) datas.Attribute("code")
                from data in datas.Elements("myData")
                select new MyData {
                    MainCode = code,
                    Code = (string) data.Attribute("name"),
                    Value = (string) data.Attribute("value"),
                };
    
    var list = query.ToList();
    

    Note the multiple from clauses to flatten the results.

    Another alternative would have been to just find all the "leaf" elements and fetch the code part from the parent:

    var query = from data in doc.Descendants("myData")
                select new MyData {
                    MainCode = (string) data.Parent.Attribute("code"),
                    Code = (string) data.Attribute("name"),
                    Value = (string) data.Attribute("value"),
                };
    
    var list = query.ToList();
    

    EDIT: If your document uses namespaces, that's easy too:

    XNamespace ns = "http://the-uri-of-the-namespace";
    var query = from data in doc.Descendants(ns + "myData")
                ...
    

    This uses the XName operator +(XNamespace, string) overloaded operator.

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