XML Array使用不带“父”数组标识符的不同类型进行序列化

问题描述 投票:1回答:1

我尝试将xml序列化(读取)到我的项目中。我无法更改该xml,因为它不是由我创建的。我试着尽可能地简化它。

我想读一个包含多种类型的数组。只要Items在[XmlArray(“”)]标记内,这就没问题了。其中一个类型可以包含具有相同类型的其他数组

例如:

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

不幸的是我有这样的事情:

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

数组元素“缺失”。通常我只是使用[XmlElemtn(“”)]标签来做这样的事情。

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

但是不可能再将XmlArrayItem标记用于不同类型。解决方法是使用多个列表/数组,如下所示:

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

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

但是我希望将所有内容放在一个列表/数组中。如果你使用这种xml序列化,这有可能吗?有没有办法使用模板?

亲切的问候

c# xml xml-serialization
1个回答
0
投票

如果其他人找到这个线程并尝试做同样的事情:有一种方法可以通过抽象类,[XmlInclude(typeof())]和[XmlElement(“”)],但它会为xml元素本身添加一个新属性。例如像p3:type =“XmlDerivedClass”。 如果要在不使用[XmlArrayItem(“node”,typeof(Node))](将额外的数组元素添加到xml)的情况下序列化具有不同类型的xml数组,则可以通过XmlIncludes执行此操作。

就像在评论中提到的那样,它看起来没有其他方式,它是如何工作的。由于我的要求,我无法以任何方式更改xml,我将通过XmlDocument或XmlReader手动完成。

© www.soinside.com 2019 - 2024. All rights reserved.