将多个 xml 元素反序列化为单个对象属性

本文关键字:单个 对象 属性 反序列化 元素 xml | 更新日期: 2023-09-27 17:56:38

>我有以下 xml

  <Amendment.Text>
    <Page>4</Page>
    <Line>4</Line>
    <Bold>It is a </Bold>   
    <Italic>Beautiful Day</Italic>
    <Bold>In London</Bold>
    <Italic>17 June 2015</Italic>   
</Amendment.Text>

我希望将<Bold><Italic>元素值反序列化为单个字符串数组属性

我的可序列化类如下所示,它不起作用。

[Serializable]
    public class AmdTextType
    {
        public string Page { get; set; }
        public string Line { get; set; }

        public string[] Content { get; set; }

    }

将多个 xml 元素反序列化为单个对象属性

为什么不从原始元素计算它:

[XmlElementAttribute("Italic", typeof(string))]        
public string Italic { get; set; }
[XmlElementAttribute("Bold", typeof(string))]
public string Bold { get; set; }
public string[] Content { 
    get {
        return new string[] { this.Italic, this.Bold };
    }
}

这是一种替代方法。 我通过使用Visual Studio中的Edit -> Paste Special-> Paste XML As类获得了大部分内容。 这还包括一系列名称,以防您需要参考粗体或斜体

[XmlType(AnonymousType = true)]
[XmlRoot("Amendment.Text", Namespace = "", IsNullable = false)]
public partial class AmendmentText
{
    [XmlElement("Line", typeof(int))]
    public int Line { get; set; }
    [XmlElement("Page", typeof(int))]
    public int Page { get; set; }
    [XmlElement("Bold", typeof(string))]        
    [XmlElement("Italic", typeof(string))]        
    [XmlChoiceIdentifier("ContentName")]
    public object[] Content { get; set; }
    [XmlElement("ContentName")]
    [XmlIgnore()]
    public ContentName[] ContentName { get; set; }
}
[XmlType(IncludeInSchema = false)]
public enum ContentName
{        
    Bold,
    Italic,        
}