简体   繁体   中英

XML Array Serialize with different types without the “parent” array identifier

I try to serialize (read) xml into my project. I can't change that xml because it is not created by me. Ill try to simplify it as much as possible.

I would like to read an array with multiple types in it. This is no problem as long as the Items are inside an [XmlArray("")] tag. One of the type can contain further arrays with the same types

For example:

Xml

<node Name="testbase">
    <items>
        <node Name="test1"/>
            <items>
                <node Name="test2"/>
                <node Name="test3"/>
            </items>
        <othernode Name="test4"/>   
    </items>
</node>

C#

public class Base
{
    [XmlAttribute("Name")]
    public string Name { get; set; }
}

public class Node : Base
{
    [XmlArray("items")]
    [XmlArrayItem("node", typeof(Node))]
    [XmlArrayItem("othernode", typeof(Othernode))]
    public Base[] nodes { get; set; }
}

public class Othernode : Base
{
}

Unfortunately I have something like this:

<node Name="testbase">
    <node Name="test1">
        <node Name="test2"/>
        <node Name="test3"/>    
    </node>
    <othernode Name="test4"/>   
</node>

The array elements are "missing". Normally I just use the [XmlElemtn("")] tag for stuff like that.

[XmlElement("node")]
public List<Node> Nodes { get; set; }

But it is not possible to use the XmlArrayItem tag for different types anymore. A work around is to just use multiple lists/arrays like this:

public class Vendor : CreateBase
{
    [XmlElement("node")]
    public List<Node> Nodes { get; set; }

    [XmlElement("othernode")]
    public List<Othernode> Othernodes { get; set; }
}

But I would love to have everything in one list/array. Is this possible in any way if you use this kind of xml serializing? Is there maybe a way to work with templates?

Kind Regards

If other people find this thread and try to do the same thing: There is a way via abstract classes, [XmlInclude(typeof())] and [XmlElement("")] but it adds a new attribute to the xml element itself. For example like this p3:type="XmlDerivedClass" .
If you want to serialize xml arrays with different types without using [XmlArrayItem("node", typeof(Node))] (that adds an extra array element to the xml) you can do that via the XmlIncludes.

Like mentioned in the comments, it looks like there is no other way and it is how it works. Because of my requirements that I cannot change the xml in any way, I will do it manually via XmlDocument or XmlReader.

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