【问题标题】:XML Serializing a List<Class>XML 序列化列表<Class>
【发布时间】:2014-05-03 02:55:40
【问题描述】:

我在反序列化 XML 时遇到问题,我不太明白。主要是,我试图避免当它们在列表中但没有成功时必须嵌套类。例如:

[XmlRoot]
[Serializable]
public class Foo
{
    [XmlElement("Bar")]
    public BarElement Bar = new BarElement();

    public class BarElement
    {
        [XmlElement("MoreBars")]
        public List<MoreElement> MoreBars = new List<MoreElement>();
    }

    [XmlRoot("More")]
    [Serializable]
    public class MoreElement
    {
        [XmlAttribute("Attribute")]
        public string Attribute { get; set; }

        [XmlText]
        public string Value { get; set; }
    }
}

对应于:

<Foo>
    <Bar>
        <MoreBars>
            <More Attribute=""></More>
            <More Attribute=""></More>
            <More Attribute=""></More>
            <More Attribute=""></More>
        </MoreBars>
    </Bar>
</Foo>

这几乎可以工作......但不完全。通过将 XmlRoot 添加到 MoreElement,我试图避免必须创建一个名为“MoreBarsElement”的新类,该类只包含一个 MoreElements 列表,因为访问“Foo.Bar.MoreBars.Value”已经很麻烦了.这可能吗?如果是这样,我该怎么做?

【问题讨论】:

    标签: c# xml


    【解决方案1】:

    回答我自己的问题 - 看起来我需要

    [XmlArray("MoreBars"), XmlArrayItem(typeof(MoreElement), ElementName = "More")]
    

    关于数组项声明。它现在可以工作了,万岁!

    【讨论】:

    • 确保将其标记为其他人的答案(点击投票下方的复选标记)。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-07-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-12
    • 2021-11-12
    相关资源
    最近更新 更多