【问题标题】:C# Deserialize XML elements with attributes into ListC# 将具有属性的 XML 元素反序列化为 List
【发布时间】:2017-11-07 20:32:37
【问题描述】:

这是 XML:

<xml id = "1234">
    <connect id="2"/>
    <connect id="1"/>
    <connect id="21"/>
    <connect id="3"/>
    <connect id="7"/>
</xml>

目前我正在这样做:

public class xml
{
    //Constructor

    [XmlAttribute ("id")]
    public uint id;

    [XmlElement ("connect")]
    public List<Connection> Connections { get; set; }

    //Deserializer
}

public class Connection
{
    [XmlAttribute ("id")]
    public uint id { get; set; }
}

目标是完全摆脱 Connection 类并将 xml 直接反序列化为:

List<uint> connections;

【问题讨论】:

    标签: c# xml xml-parsing xml-deserialization


    【解决方案1】:

    首先,您的 XML 无效,我想这只是一个错字 - "connect" 没有结束标记。

    我推荐你使用 linq XDocument.
    那么就很简单了:

    XDocument xdoc = XDocument.Parse(xml);
    List<uint> list = xdoc
                        .Descendants("connect")
                        .Select(node => uint.Parse(node.Attribute("id").Value))
                        .ToList();
    

    【讨论】:

    • 有没有办法使用System.Xml.Serialization实现这一点?
    • 谢谢!这正是我正在寻找的解决方案。我没有意识到 XDocument 的潜力。
    • &lt;connect /&gt; 正在自动关闭。那为什么它不应该是有效的呢?
    • @da_berni,问题在我发布后已被编辑和修复
    猜你喜欢
    • 2012-05-09
    • 1970-01-01
    • 2012-12-24
    • 1970-01-01
    • 2021-12-13
    • 1970-01-01
    • 1970-01-01
    • 2023-03-08
    • 1970-01-01
    相关资源
    最近更新 更多