开发者

Xml Serialization - ignore parent node

开发者 https://www.devze.com 2023-03-06 16:47 出处:网络
I have the following class: public class product { public string name { get; set; } [XmlElement(\"AreaImageCaption\")]

I have the following class:

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

When I serialize it, it outputs the following 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>

But I need it to hide the "AreaImageCaption" node, so it would look like this:

    <?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>

Any ideas on how to accomplish this?

Thanks


Just for the sake of serialization, create two more properties like your images one:

[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();
    }
}

You will also need to mark your AreaImageCaptions with an [XmlIgnore] attrbute to avoid double entries.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号