简体   繁体   中英

Deserialize XML to C# object with arbitrary nested XML

So I have searched all I can, but cannot find the exact problem I am encountering.

This is my nested XML:

<Message>
    <Foo>
        <Bar>1</Bar>
        <Baz>2</Baz>
        <Qux>3</Qux>
    </Foo>
</Message>

And I have a class in C#:

[Serializable()]
[XmlRoot("Message")]
public class Foo
{
    [XmlElement("Bar")]
    public string Bar { get; set; }
    [XmlElement("Baz")]
    public string Baz { get; set; }
    [XmlElement("Qux")]
    public string Qux { get; set; }
}

Now Message is just arbitrary and gets sent with every XML message. So every XML message sent will have a <Message> tag around it. When I put Foo as the XmlRoot it throws an error, and with Message as XmlRoot it doesn't recognize the child elements. I am looking for a clean and easy solution to this. Thanks!

I haven't tested this, but it should work.

[Serializable()]
[XmlRoot("Message")]
public class Message
{
    [XmlElement("Foo")]
    public Foo Foo { get; set; }
}

[Serializable()]
public class Foo
{
    [XmlElement("Bar")]
    public string Bar { get; set; }
    [XmlElement("Baz")]
    public string Baz { get; set; }
    [XmlElement("Qux")]
    public string Qux { get; set; }
}

Use to get correct model here link

After that you can these methods to serialize and deserialize:

    public static class XMLFactory
{
    public static T XmlDeserializeFromString<T>(this string objectData)
    {
        return (T)XmlDeserializeFromString(objectData, typeof(T));
    }
    public static object XmlDeserializeFromString(this string objectData, Type type)
    {
        try
        {
            var serializer = new XmlSerializer(type);
            object result;

            using (TextReader reader = new StringReader(objectData))
            {
                result = serializer.Deserialize(reader);
            }

            return result;
        }
        catch (Exception ex)
        {
            LoggerHelper.LogError(ex.ToString());
            return null;
        }
    }
    public static string XmlSerializeToString(this object objectInstance)
    {
        var serializer = new XmlSerializer(objectInstance.GetType());
        var sb = new StringBuilder();

        using (TextWriter writer = new StringWriter(sb))
        {
            serializer.Serialize(writer, objectInstance);
        }

        return sb.ToString();
    }
}

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