简体   繁体   中英

Serialize XML array, attribute to Object

How Can I define an object to deserialize the following XML:

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

I'd strongly recommend to use xsd.exe , which can help in generating XML schema or common language runtime classes from XDR, XML, and XSD files, or from classes in a runtime assembly.

  1. Open VS Developer Command Prompt
  2. Type xsd.exe PathToXmlFile.xml /outputdir:OutputDir and press Enter - this will generate *.xsd file
  3. Type xsd.exe PreviouslyCreatedXsdFile.xsd /classes /outputdir:OutputDir and press Enter - this will generate *.cs file (class definition).

That's all!

Try!

Try this....

Usings.....

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

Classes.....

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

Code.....

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

Your XML.....

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

I added the end tag..... I am reading your XML in to a string from a file in the application build folder called xml.xml... you will need to get the XML string from somewhere else or create the xml.xml file and save your XML for the code above to work

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM