使用C#读取具有重复结构的XML文件

本文关键字:结构 XML 文件 读取 使用 | 更新日期: 2023-09-27 18:28:35

我有一个描述连接的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文件

您可以使用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文件包含一个&字符,该字符将丢弃XML文档负载。我可以通过用&amp; 替换"与"来运行上面的代码

您必须创建一个包装类型来包含连接列表,因为它不知道<connections>是什么,然后通过在每个字段中添加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; 转义

试试这个。最佳方法

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; }
    }
}
​