代码之家  ›  专栏  ›  技术社区  ›  David Neale

XML序列化查询

  •  2
  • David Neale  · 技术社区  · 14 年前

    我有以下需要反序列化/序列化的XML:

    <instance>
    <dog>
        <items>
            <item>
                <label>Spaniel</label>
            </item>
        </items>
    </dog>
    <cat>
        <items>
            <item>
                <label>Tabby</label>
            </item>
        </items>
    </cat>
    </instance>
    

    我无法更改XML结构。

    我需要将此映射到以下类:

    [Serializable, XmlRoot("instance")]
    public class AnimalInstance
    {
        public string Dog { get; set; }
        public string Cat { get; set; }
    }
    

    如果不手动解析XML,我真的不确定从何处开始。我想尽量简明扼要地编写代码。有什么想法吗?(不,我的项目实际上并不涉及猫和狗)。

    5 回复  |  直到 14 年前
        1
  •  6
  •   Paolo Tedesco    14 年前

    使用 System.Xml.Serialization :

    using System.Collections.Generic;
    using System.IO;
    using System.Xml.Serialization;
    
    [XmlRoot("instance")]
    public class AnimalInstance {
        [XmlElement("dog")]
        public Dog Dog { get; set; }
    }
    
    public class Dog {
        [XmlArray("items")]
        [XmlArrayItem("item")]
        public List<Item> Items = new List<Item>();
    }
    
    public class Item {
        [XmlElement("label")]
        public string Label { get; set; }
    }
    
    class Program {
        static void Main(params string[] args) {
            string xml = @"<instance>
    <dog>
        <items>
            <item>
                <label>Spaniel</label>
            </item>
        </items>
    </dog>
    </instance>";
    
            XmlSerializer xmlSerializer = new XmlSerializer(typeof(AnimalInstance));
            AnimalInstance instance = (AnimalInstance)xmlSerializer.Deserialize(new StringReader(xml));
        }
    }
    
        2
  •  2
  •   Mark Heath    14 年前

    为什么编写自定义解析代码会出现这样的问题?对于您的简单示例,使用xdocument实际上可能需要较少的代码:

    XDocument xdoc = XDocument.Parse(xml);
    AnimalInstance animal = new AnimalInstance()
    {
        Dog = xdoc.XPathSelectElement("instance/dog/items/item/label").Value,
        Cat = xdoc.XPathSelectElement("instance/cat/items/item/label").Value
    };
    
        3
  •  1
  •   Doug    14 年前

    当对创建XML序列化类有疑问时,我发现解决此问题的最简单方法是:

    • 将所有虚拟数据转储到XML文件中
    • 运行xsd.exe创建.xsd架构文件
    • 在架构文件上运行xsd.exe以创建类文件

    不久前,我在一篇博客文章中写了一篇关于它的快速教程: http://www.diaryofaninja.com/blog/2010/05/07/make-your-xml-stronglytyped-because-you-can-and-its-easy

    只需不到一分钟,你就可以轻松地从那里调整。XSD.exe是你的 朋友

        4
  •  0
  •   Arseny    14 年前

    那么,您可以通过IXML可序列化接口进行自定义序列化,以获得所需的结构。

        5
  •  0
  •   Scoregraphic    14 年前

    您还可以使用XSL将XML文档转换为您喜欢的结构,并反序列化此转换的输出。但对于这样一个简单的结构,您应该使用另一种解决方案,如paolo tedesco提供的解决方案。