簡體   English   中英

序列化XML數組,屬性為Object

[英]Serialize XML array, attribute to Object

如何定義對象以反序列化以下XML:

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

我強烈建議使用xsd.exe ,它可以幫助從XDR,XML和XSD文件或從運行時程序集中的類生成XML模式或公共語言運行時類。

  1. 打開VS Developer命令提示符
  2. 鍵入xsd.exe PathToXmlFile.xml /outputdir:OutputDir並按Enter -這將生成*.xsd文件
  3. 鍵入xsd.exe PreviouslyCreatedXsdFile.xsd /classes /outputdir:OutputDir並按Enter -這將生成*.cs文件(類定義)。

就這樣!

嘗試!

嘗試這個....

正在使用.....

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以使上面的代碼正常工作

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM