Xml序列化 - 忽略父节点

时间:2011-05-17 10:32:51

标签: c# asp.net xml serialization xml-serialization

我有以下课程:

    public class product 
    {
        public string name { get; set; }

        [XmlElement("AreaImageCaption")]
        public List<AreaImageCaption> AreaImageCaptions { get; set; }

        [XmlElement("image")]
        public List<string> images { get; set; }
    }

    public class AreaImageCaption
    {
        public string area_image { get; set; }
        public string area_caption { get; set; }
    }

当我序列化它时,它会输出以下XML:

    <?xml version="1.0"?>
    <products>
        <product>
            <name>100</name>
            <AreaImageCaption>
                <area_image>image1</area_image>
                <area_caption>caption1</area_caption>
            </AreaImageCaption>
            <AreaImageCaption>
                <area_image>image2</area_image>
                <area_caption>caption2</area_caption>
            </AreaImageCaption>
            <image>img1.jpg</image>
            <image>img2.jpg</image>
        </product>
    </products>

但我需要它来隐藏“AreaImageCaption”节点,所以它看起来像这样:

    <?xml version="1.0"?>
<products>
    <product>
        <name>100</name>

        <area_image>image1</area_image>
        <area_caption>caption1</area_caption>
        <area_image>image2</area_image>
        <area_caption>caption2</area_caption>

        <image>img1.jpg</image>
        <image>img2.jpg</image>
    </product>
</products>

关于如何实现这一目标的任何想法?

由于

1 个答案:

答案 0 :(得分:0)

仅为了序列化,再创建两个属性,例如images一个:

[XmlElement("area_caption")]
public List<string> area_captions 
{ 
    get
    {
        return (from item in AreaImageCaptions select item.area_caption).ToList();
    }
}
[XmlElement("area_image")]
public List<string> area_images
{ 
    get
    {
        return (from item in AreaImageCaptions select item.area_image).ToList();
    }
}

您还需要将AreaImageCaptions标记为[XmlIgnore] attrbute以避免重复输入。