简体   繁体   中英

Using XMLReader to read large XML documents to parse the information into a class

I have been using XDocument combined with LINQ to XML to load in xml files and populate my class.

But now I am tasked with making sure my program can handle all sizes of XML documents which means i need to use XML Reader and at this time being i cant get my head around manipulating the XMLReader to populate my class.

currently i have the below class to populate:

 public class DataRecord
  {
    private List<Fields> field = new List<Fields>();

    public string ID { get; set; }
    public string TotalLength { get; set; }

    public List<Fields> MyProperty
    {
      get { return field; }
      set { field = value; }
    }

  }

  internal class Fields
  {
    public string name { get; set; }
    public string startByte { get; set; }
    public string length { get; set; }
  }

}

I have been trying to switch statements to enforce the xmlreader to provide the data from me to populate the class. For example:

using (XmlReader reader = XmlReader.Create(filename))
  {
    while (reader.Read())
    {
      switch (reader.NodeType)
      {
        case XmlNodeType.Element:
          switch (reader.Name)
          {
            case "DataRecord":
              var dataaa = new dataclass.DataRecord();
              break;
          }
         break;
      }
    }
  }

But as i said this is an example, I have searched for ages to try and find an answer but I am getting confused. Hopefully someone can help we my problem.

You can use XmlReader to move through the document, but then load each element using XElement.

Here's a short example:

using System;
using System.Xml;
using System.Xml.Linq;

class Test
{
    static void Main()
    {
        using (var reader = XmlReader.Create("test.xml"))
        {
            while (reader.ReadToFollowing("foo"))
            {
                XElement element = XElement.Load(reader.ReadSubtree());
                Console.WriteLine("Title: {0}", element.Attribute("title").Value);
            }
        }
    }
}

With sample XML:

<data>
  <foo title="x" /><foo title="y">asd</foo> <foo title="z" />
</data>

(Slightly inconsistent just to show that it can handle elements with content, elements with no space between them, and elements with space between them.)

Then obviously in the loop you'd do whatever you need to with the XElement - if you've already got a way of creating an instance of your class from an XElement , you can just call that, use the object, and you're away.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM