C# Xml序列化-忽略父节点
我有以下课程:C# Xml序列化-忽略父节点,c#,asp.net,xml,serialization,xml-serialization,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&
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; }
}
公共类产品
{
公共字符串名称{get;set;}
[XmlElement(“AreaImageCaption”)]
公共列表区域图像标题{get;set;}
[XmlElement(“图像”)]
公共列表图像{get;set;}
}
公共类图片标题
{
公共字符串区域\图像{get;set;}
公共字符串区域_标题{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>
100
图1
标题1
图2
标题2
img1.jpg
img2.jpg
但是我需要它来隐藏“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>
100
图1
标题1
图2
标题2
img1.jpg
img2.jpg
关于如何实现这一点有什么想法吗
谢谢为了实现序列化,请再创建两个属性,如您的
图像
一个:
[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();
}
}
[xmlement(“区域标题”)]
公共列表区域\标题
{
得到
{
返回(从AreaImageCaptions中的项目选择item.area_caption.ToList();
}
}
[XmlElement(“区域图像”)]
公共列表区图片
{
得到
{
返回(从area ImageCaptions中的项目选择item.area_image.ToList();
}
}
您还需要使用
[XmlIgnore]
属性标记区域图像标题
,以避免重复输入。您确定它会输出您显示的XML吗?这两个元素之间不是有一个AreaImageCaption
关闭和打开节点吗?是的,你说得对。它在2个元素周围有一个AreaImageCaption标记。我刚刚编辑了代码。关于如何隐藏它有什么想法吗?@user441365,这个标签是故意的。如果删除它,您将无法再区分列表中的不同元素。@Darin Dimitrov,是的,您可能是对的,但我确实需要删除它,这不会破坏XML验证。有什么想法吗?@user441365,我的观点是,即使这不会破坏XML验证,它也会破坏语义=>您不能再使用列表作为对象。嗯,这会使XML标记以另一种顺序出现(所有标题,然后是所有图像)。这不会使它显示所有区域标题,然后是所有区域图像,而不是把它们配对?