使用LINQ读取xml并存储在对象列表中

时间:2014-11-25 06:02:49

标签: c# xml linq

我有以下格式的xml文件:

<TestDataFile name="Register">
<TestSuite name="Positive">
<TestCase>
  <StoryName>Register user</StoryName>
  <ScenarioName>Positive</ScenarioName>
  <TestCaseName>Register new user</TestCaseName>
  <ResponseCode>200</ResponseCode>
  <UserDetails>
    <DateOfBirth></DateOfBirth>
  </UserDetails>
</TestCase>
<TestCase>
  <StoryName>Register user</StoryName>
  <ScenarioName>Positive</ScenarioName>
  <TestCaseName>Register new user</TestCaseName>
  <ResponseCode>200</ResponseCode>
  <UserDetails>
    <DateOfBirth></DateOfBirth>
  </UserDetails>
 </TestCase>
 </TestSuite>
 <TestSuite name="Negative">
 <TestCase>
  <StoryName>Register user</StoryName>
  <ScenarioName>Positive</ScenarioName>
  <TestCaseName>Register new user</TestCaseName>
  <ResponseCode>200</ResponseCode>
  <UserDetails>
    <DateOfBirth></DateOfBirth>
  </UserDetails>
  </TestCase>
 <TestCase>
  <StoryName>Register user</StoryName>
  <ScenarioName>Positive</ScenarioName>
  <TestCaseName>Register new user</TestCaseName>
  <ResponseCode>200</ResponseCode>
  <UserDetails>
    <DateOfBirth></DateOfBirth>
  </UserDetails>
  </TestCase>
  </TestSuite>
 </TestDataFile>

以此格式包含许多xml文件。我想读取所有xmls并使用LINQ存储在List:List中。尝试使用以下代码实现它但不起作用:

foreach (string file in files)
        {
            TestDataFile testData = new TestDataFile();
            var doc = XDocument.Load(file);
            var result = doc.Descendants("TestDataFile")
                .Select(x => new TestDataFile
                {
                    TestSuites = new List<TestSuite>
                    (from ts in doc.Descendants("TestSuite")
                     select new TestSuite
                     {
                         TestCases = new List<TestCase>(from test in doc.Descendants("TestCase")
                                                        select new TestCase
                                                        {
                                                            StoryName = x.Element("StoryName").Value
                                                        })
                     })
                });

        }

有人可以帮帮我吗?

2 个答案:

答案 0 :(得分:2)

试试这个: -

var result = XDocument.Load(@"Path\Data.xml").Root.Descendants("TestCase")
                       .Select(x => new TestCase 
                       {
                           StoryName = x.Element("StoryName").Value,
                           ScenarioName = x.Element("ScenarioName").Value,
                           TestCaseName = x.Element("TestCaseName").Value,
                           ResponseCode = Convert.ToInt32(x.Element("ResponseCode").Value),
                           userDetails = x.Descendants("UserDetails")
                                          .Select(z => new UserDetail 
                                            { 
                                                 DateOfBirth = !String.IsNullOrEmpty(z.Element("DateOfBirth").Value) ?
                                                               Convert.ToDateTime(z.Element("DateOfBirth").Value) : DateTime.MinValue }).FirstOrDefault()
                                            }).ToList();

我使用了以下类型: -

public class TestCase
{
    public string StoryName { get; set; }
    public string ScenarioName { get; set; }
    public string TestCaseName { get; set; }
    public int ResponseCode { get; set; }
    public UserDetail userDetails { get; set; }
}

public class UserDetail
{
    public DateTime DateOfBirth { get; set; }
}

修改

我认为您的UserDetail在TestCase类型中不是List,因此根据该假设更新了代码。

答案 1 :(得分:0)

您可以使用以下代码序列化和反序列化任何对象。 在你的情况下,TestDataFile的对象应该是obj。在TestDataFile中,您应该声明TestSuite的属性,并在其中声明TestCase的Type List属性。

获取XML文件这是我的代码:

 TextReader Treader = null;
 Treader = new StreamReader(fullFileName);
 ContactsModel = (ContactsDBModel)OSINFO.FromXml<ContactsDBModel>(Treader);

助手的内容如下:

public static string ToXml(object obj)
    {
        XmlSerializer s = new XmlSerializer(obj.GetType());
        using (StringWriterWithEncoding writer = new StringWriterWithEncoding(Encoding.UTF8))
        {
            s.Serialize(writer, obj);
            return writer.ToString();
        }
    }

    public static object FromXml<T>(this TextReader data)
    {
        XmlSerializer s = new XmlSerializer(typeof(T));
        object obj = s.Deserialize(data);
            return (T)obj;
    }

我为UTF8编码添加了一个自定义类StringWriterWithEncoding。

public class StringWriterWithEncoding : StringWriter
{
    public StringWriterWithEncoding(StringBuilder sb, Encoding encoding)
        : base(sb)
    {
        this.m_Encoding = encoding;
    }

    public StringWriterWithEncoding(Encoding encoding)
        : base()
    {
        this.m_Encoding = encoding;
    }

    private readonly Encoding m_Encoding;
    public override Encoding Encoding
    {
        get
        {
            return this.m_Encoding;
        }
    }
}