【问题标题】:C# - using Linq to XML to populate list of objectsC# - 使用 Linq to XML 填充对象列表
【发布时间】:2014-01-27 02:52:36
【问题描述】:

我正在尝试使用 XML 文件的内容作为对象列表的数据源。对象如下所示:

public class QuestionData
{
public string QuestionName{get;set;}
public List<string> Answers{get;set;}
}

这是我的 XML:

<?xml version="1.0" encoding="utf-8" ?>
<QuestionData>
    <Question>
        <QuestionName>Question 1</QuestionName>
        <Answers>
            <string>Answer 1</string>
            <string>Answer 2</string>
            <string>Answer 3</string>
            <string>Answer 4</string>
        </Answers>
    </Question>
    <Question>
        <QuestionName>Question 2</QuestionName>
        <Answers>
            <string>Answer 1</string>
            <string>Answer 2</string>
            <string>Answer 3</string>
        </Answers>
    </Question>
</QuestionData>

我用来尝试执行此操作的代码是:

var xml = XDocument.Load ("C:\temp\xmlfile.xml");

List<QuestionData> questionData = xml.Root.Elements("Question").Select 
(q => new QuestionData {
  QuestionName = q.Element ("QuestionName").Value, 
  Answers = new List<string> { 
    q.Element ("Answers").Value }
}).ToList ();

代码可以编译,但我没有从 XML 中获取任何数据。我通过 questionData 循环尝试将信息显示到控制台,但它是空的。

【问题讨论】:

    标签: c# xml linq linq-to-xml


    【解决方案1】:
    List<QuestionData> questionData =
        xml.Root
           .Elements("Question")
           .Select(q => new QuestionData
                         {
                             QuestionName = (string)q.Element("QuestionName"),
                             Answers = q.Element("Answers")
                                        .Elements("string")
                                        .Select(s => (string)s)
                                        .ToList()
                         }).ToList();
    

    我使用(string)XElement 转换而不是XElement.Value 属性,因为当元素为null 时它不会抛出NullReferenceException

    【讨论】:

    • 是否可以为从 xml 引入的每个答案项也包含一个布尔值?我想让每个答案的默认选择状态为假,所以我想可能将 QuestionData 类中的 Answers 属性更改为public List&lt;Tuple&lt;string, bool&gt;&gt; Nominees { get; set; },然后尝试Answers = new Tuple&lt;string,bool&gt; (q.Element("Answers").Elements("string").Select(s =&gt; (string)s), false).ToList() 之类的东西,但我收到一个隐式转换错误那个代码。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多