XML parsing and saving to an object

I would like to parse an XML file and store this information in an object. What is the best way to do this? Please let me know.

Thanks..

+3
source share
3 answers

If you are using .Net 3.5, I would suggest using LINQ-To-XML.

A simple example ...

Xml file

 <?xml version="1.0" ?> 
 <People>
      <Person>
          <Name> ABC </Name>
          <SSN> 111111 </SSN>
          <Address> asdfg </Address>
      </Person>
 </People>

LINQ query

XDocument doc = XDocument.Load(pathToFile);
var query = from d in doc.Root.Descendants("Person")
            select d;

foreach (var q in query)
{
    string name = q.Element("Name").Value;
    string ssn = q.Element("SSN").Value;
    string address = q.Element("Address").Value;
}
+5
source

You can use XmlSerializer for deserialization.

using System;
using System.IO;
using System.Xml.Serialization;

[XmlRoot("Root")]
public class MyType
{
    [XmlElement("Id")]
    public string Id { get; set; }
    [XmlElement("Name")]
    public string Name { get; set; }
}

static class Program
{
    static void Main()
    {
        string xml = @"<Root>
                          <Id>1</Id>
                          <Name>The Name</Name>
                      </Root>";
        MyType obj = (MyType) new XmlSerializer(typeof(MyType))
            .Deserialize(new StringReader(xml));
        Console.WriteLine(obj.Id);
        Console.WriteLine(obj.Name);
    }
};
+8
source

, ( IntelliSense ). , "node " , ( ).

Or you can try the C # 4.0 dynamic keyword, this can give you a choice not to generate code and just deserialize at runtime. But I'm not so sure about that. This way you lose strong typing, but retain the syntax.

+1
source

Source: https://habr.com/ru/post/1719618/


All Articles