Linq To XML - 使用XDocument并创建对象列表

时间:2012-11-13 11:42:03

标签: c# xml linq

我必须阅读XML文档并将值插入到List<T>个对象中。

类(结果)

+Result
-username
-dob
-answer1
-answer2
-uuid

以下是XML格式结构

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<export exportDate="2012-11-07T12:03:52.823+11:00">
    <survey type="USER" completion="2012-11-07T11:46:52.754+11:00" reference="2012-11-07T11:30:34.680+11:00" year="2012" uuid="226f2aa3-46e6-46ab-8995-7d52eb21d5f4">
        <user xsi:type="USER" created="2012-11-07T11:09:30.409+11:00" dob="08/06/1988" surname="Billy" name="Bob" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"/>
        <subject created="2012-11-07T11:09:30.409+11:00" dob="08/06/1988" surname="Billy" name="Bob"/>
        <version released="1970-01-01T10:00:02.012+10:00" version="1"/>
        <result group="2" rawscore="2.4" metric="1"/>
        <result group="2" rawscore="2.0" metric="2"/>
        <answer score="1" question="6"/>
        <answer score="2" question="7"/>
    </survey>       
</export>

我目前的进展

我之前使用的是 XmlDocument ,但现在我正在与Linq合作,我确定这可以在几行内完成。我不喜欢下面代码的外观,如果有任何提示请帮忙。

三江源

    List<Result> results = new List<Result>();

    XmlDocument doc = new XmlDocument();
    doc.Load(filename); 

    XmlNodeList objects = doc.GetElementsByTagName("survey"); 
    foreach (XmlNode o in objects)
    {
        Result result = new Result();

        if (o.Attributes["type"].Value == "USER" || o.Attributes["type"].Value == "ADMIN")
        {
            result.surveycompleted = o.Attributes["completion"].Value;

            XmlNodeList usernodes = o.SelectNodes("user");
                ....
            if (usernodes.Count > 0)
            {}
            else
            { 

1 个答案:

答案 0 :(得分:3)

使用LINQ2XML:

XElement doc=XElement.Load(filename);
List<Result> lstSurvey=doc.DescendantsAndSelf("Survey").Select(x=>
new Result
{
    uuid=x.Element("Survey").Attribute("uuid").Value,
    username=x.Element("user").Attribute("name").Value,
    dob=x.Element("user").Attribute("dob").Value,
    answer1=x.Elements("answer").First().Value,
    answer2=x.Elements("answer").Skip(1).First().Value
}
).ToList<Result>();