Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

c# - XDocument to List of object

The content of an XDocument is the XML below.

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

<myXml>
  <myDatas code="01">
    <myVar name="myvar" value="A" />
    <myData name="A" value="A1" />
    <myData name="B" value="B1" />
  </myDatas>
  <myDatas code="02">
    <myVar name="myvar" value="B" />
    <myData name="A" value="A2" />
    <myData name="D" value="D2" />
  </myDatas>
</myXml>

public class MyData
{
    public string MainCode { get; set; }
    public string Code { get; set; }
    public string Value { get; set; }
}

I'd like a List() this content should be like this :

new MyData { MainCode = "01"; Code = "A"; Value = "A1" };
new MyData { MainCode = "01"; Code = "B"; Value = "B1" };
new MyData { MainCode = "02"; Code = "A"; Value = "A2" };
new MyData { MainCode = "02"; Code = "D"; Value = "D2" };
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...