解析XML并保存到对象中

4 c#

我想解析一个XML文件并将此信息保存到对象中.做这个的最好方式是什么?请告诉我.

谢谢..

Paw*_*ski 9

您可以使用XmlSerializer对其进行反序列化.

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);
    }
};
Run Code Online (Sandbox Code Playgroud)


Rya*_*ord 5

如果您使用的是.Net 3.5,我建议使用LINQ-To-XML.

一个简单的例子......

XML文件

 <?xml version="1.0" ?> 
 <People>
      <Person>
          <Name> ABC </Name>
          <SSN> 111111 </SSN>
          <Address> asdfg </Address>
      </Person>
 </People>
Run Code Online (Sandbox Code Playgroud)

LINQ查询

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;
}
Run Code Online (Sandbox Code Playgroud)