Search code examples
c#xmlxmlreader

Read an XML File and transform data into a list of DirectoryInfo elements


I'm currently trying to read an XML file of this format to transform it into a list but trying out the code in the comments gave me an error: this is how it looks like in IE. Obviously theres a close assets tag and close properties later

  <Properties>
- <Assets>
- <Asset Name="" Version="">
  <TestCase Name="" Version="" SubVersion="" /> 
  <TestCase Name="" Version="" SubVersion="" /> 
  <TestCase Name="" Version="" SubVersion="" /> 
  <TestCase Name="" Version="" SubVersion="" />  
  </Asset>

So I did this:

XmlReader xReader = XmlReader.Create(new StringReader(xmlDoc));

where xml doc = @"\\visreP01\REFERENCES\default.reference.versions\default.reference.versions.properties.xml"

I'm planning to test how to iterate a name a version and so on to place them in a list iteratively. but during the reading the I got the data root level is invalid line 1 position 1.


Solution

  • Try this

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.IO;
    using System.Xml;
    using System.Xml.Linq;
    
    namespace ConsoleApplication1
    {
        class Program
        {
            const string FILENAME = @"c:\temp\test.xml";
            static void Main(string[] args)
            {
    
                XmlReader xReader = XmlReader.Create(FILENAME);
    
                while(!xReader.EOF)
                {
                    if (xReader.Name != "Asset")
                    {
                        xReader.ReadToFollowing("Asset");
                    }
                    if (!xReader.EOF)
                    {
                        XElement assets = (XElement)XElement.ReadFrom(xReader);
                        var results = assets.Elements("TestCase").Select(x => new
                        {
                            name = (string)x.Attribute("Name"),
                            version = (string)x.Attribute("Version"),
                            subVersion = (string)x.Attribute("SubVersion")
                        }).ToList();
    
    
                     }
                }
            }
        }
    }