【问题标题】:Reading XML files with repeating structures using C#使用 C# 读取具有重复结构的 XML 文件
【发布时间】:2015-12-31 01:15:32
【问题描述】:

我有一个描述连接的 XML 文件,即

    <?xml version="1.0" encoding="utf-8"?>
    <connections>
      <connection name="Local server remote">
        <ip>192.168.0.7        </ip>
        <port>23        </port>
        <description>
          Remote controlling of that nice & neat box under the table.
        </description>
        </connection>
        <connection name="Far, far away server HTTP access">
          <ip>77.32.57.144        </ip>
          <port>8080        </port>
          <description>
            A legend tells of a far, far away country of Russia, and of a server somewhere inside this mysterious country.
          </description>
        </connection>
      </connections>

有没有一种简单的方法可以将该 XML 文件解析为如下类的对象:

    class Connection {
        public string Name;
        public string IP;
        public int Port;
        public string Description;
     }

?

【问题讨论】:

标签: c# xml oop parsing deserialization


【解决方案1】:

您可以使用 Linq to XML 来阅读:

var xmlDoc = XDocument.Load("XMLFile1.xml");
if(xmlDoc.Root != null)
{
    var connections = (xmlDoc.Root.Elements("connection").Select(e => new Connection
    {
        Description = (string) e.Element("description"),
        IP = (string) e.Element("ip"),
        Name = (string) e.Element("name"),
        Port = (int) e.Element("port")
    })).ToList();
}

可能值得指出的是,您的 XML 文件包含一个 &amp;amp; 字符,这会导致 XML 文档加载失败。我可以通过用 &amp;amp; 替换 & 符来运行上面的代码

【讨论】:

    【解决方案2】:

    您必须创建一个包装器类型来包含连接列表,因为它不知道 &lt;connections&gt; 是什么,然后通过为每个字段添加一个 XmlElement 名称来处理其余部分。

    public static void Main(string[] args)
    {
        var serializer = new XmlSerializer(typeof (ConnectionList));
    
        var connections = ((ConnectionList)serializer.Deserialize(new StreamReader("data.xml"))).Connections;
        foreach (var connection in connections)
        {
            Console.WriteLine(connection.IP);
        }
        Console.ReadLine();
    }
    
    [XmlRoot("connections")]
    public class ConnectionList
    {
        [XmlElement("connection")]
        public List<Connection> Connections { get; set; } = new List<Connection>();
    }
    
    [XmlType("connection")]
    public class Connection
    {
        [XmlElement("description")] public string Description;
    
        [XmlElement("ip")] public string IP;
    
        [XmlElement("name")] public string Name;
    
        [XmlElement("port")] public int Port;
    }
    

    注意:XML 中的“&”是无效字符,必须转义为&amp;amp;

    【讨论】:

      【解决方案3】:

      试试这个。最佳方法

      using System;
      using System.Collections.Generic;
      using System.Linq;
      using System.Text;
      using System.Xml;
      using System.Xml.Linq;
      
      namespace ConsoleApplication1
      {
          class Program
          {
              const string FILENAME = @"c:\temp\test.xml";
              static void Main(string[] args)
              {
                  XDocument doc = XDocument.Load(FILENAME);
                  List<Connection> connections = doc.Descendants("connection").Select(x => new Connection(){
                      Name = x.Attribute("name").Value,
                      IP = x.Element("ip").Value,
                      Port = int.Parse(x.Element("port").Value),
                      Description = x.Element("description").Value,
                  }).ToList();
              }
          }
          public class Connection
          {
              public string Name { get; set; }
              public string IP { get; set; }
              public int Port { get; set; }
              public string Description { get; set; }
          }
      }
      ​
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-05-19
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多