【问题标题】:Serialize XML array, attribute to Object序列化 XML 数组,属性为 Object
【发布时间】:2016-04-13 16:55:21
【问题描述】:

我如何定义一个对象来反序列化以下 XML:

<body>
<S1 A="1">
    <S2 B="1">
        <S3 C="1"/>
        <S3 C="1"/>
    </S2>
    <S2 B="2"/>
</S1>
<S1 A="2"/>

【问题讨论】:

  • 定义什么?你能说得更具体点吗?
  • 有大量关于如何将 xml 反序列化为对象的示例。你必须表现出一些努力。
  • 你能用格式良好的 XML 举个例子吗?

标签: c# xml wcf xml-serialization


【解决方案1】:

我强烈建议使用xsd.exe,它可以帮助从 XDR、XML 和 XSD 文件或从运行时程序集中的类生成 XML 架构或公共语言运行时类。

  1. 打开VS Developer Command Prompt
  2. 键入xsd.exe PathToXmlFile.xml /outputdir:OutputDir 并按Enter - 这将生成*.xsd 文件
  3. 键入xsd.exe PreviouslyCreatedXsdFile.xsd /classes /outputdir:OutputDir 并按Enter - 这将生成*.cs 文件(类定义)。

就是这样!

试试吧!

【讨论】:

    【解决方案2】:

    试试这个....

    用途.....

    using System;
    using System.Xml.Serialization;
    using System.Collections.Generic;
    using System.IO;
    using System.Text;
    using System.Xml;
    

    类.....

    [XmlRoot(ElementName = "S3")]
    public class S3
    {
        [XmlAttribute(AttributeName = "C")]
        public string C { get; set; }
    }
    
    [XmlRoot(ElementName = "S2")]
    public class S2
    {
        [XmlElement(ElementName = "S3")]
        public List<S3> S3 { get; set; }
        [XmlAttribute(AttributeName = "B")]
        public string B { get; set; }
    }
    
    [XmlRoot(ElementName = "S1")]
    public class S1
    {
        [XmlElement(ElementName = "S2")]
        public List<S2> S2 { get; set; }
        [XmlAttribute(AttributeName = "A")]
        public string A { get; set; }
    }
    
    [XmlRoot(ElementName = "body")]
    public class Body
    {
        [XmlElement(ElementName = "S1")]
        public List<S1> S1 { get; set; }
    }
    

    代码.....

            string strXML = File.ReadAllText("xml.xml");
            byte[] bufXML = ASCIIEncoding.UTF8.GetBytes(strXML);
            MemoryStream ms1 = new MemoryStream(bufXML);
    
            // Deserialize to object
            XmlSerializer serializer = new XmlSerializer(typeof(Body));
            try
            {
                using (XmlReader reader = new XmlTextReader(ms1))
                {
                    Body deserializedXML = (Body)serializer.Deserialize(reader);
    
                }// put a break point here and mouse-over deserializedXML….
            }
            catch (Exception ex)
            {
                throw;
            }
    

    你的 XML.....

    <body>
    <S1 A="1">
        <S2 B="1">
            <S3 C="1"/>
            <S3 C="1"/>
        </S2>
        <S2 B="2"/>
    </S1>
    <S1 A="2"/>
    </body>
    

    我添加了结束标记.....我正在从应用程序构建文件夹中名为 xml.xml 的文件中将您的 XML 读入字符串...您将需要从其他地方获取 XML 字符串或创建xml.xml 文件并保存您的 XML 以使上面的代码正常工作

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-11-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-20
      相关资源
      最近更新 更多