Anil Kumar B
Anil Kumar B

Reputation: 119

Read xml using LINQ and store in a list of objects

I have xml files in the following format:

<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>

Have many xml files in this format. And I want to read all the xmls and store in a List: List using LINQ. Trying to achieve it with the following code but not working:

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
                                                        })
                     })
                });

        }

Can someone please help me ?

Upvotes: 3

Views: 1299

Answers (2)

Rahul Singh
Rahul Singh

Reputation: 21795

Try this:-

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();

Where I have used following Types:-

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; }
}

Edit:

I think your UserDetail will not be a List in TestCase Type, so updated the code based on that assumption.

Upvotes: 2

Sandeep Ray
Sandeep Ray

Reputation: 27

You can use following code to serialize and deserialize any object. In your case object of TestDataFile should be the obj. Inside TestDataFile you should declare a property of TestSuite and inside it a property of Type List of TestCase.

To get the XML file Here is My Code:

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

Helper clases are as follows:

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;
    }

i have added a customized class StringWriterWithEncoding for UTF8 encoding.

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;
        }
    }
} 

Upvotes: 0

Related Questions