我想将以下类序列化为xml:
public class Survey
{
[XmlElement("edit")]
public string EditLink { get; set; }
}
正如预期的那样序列化为(删除了对问题不重要的额外内容)
<Survey><edit>http://example.com/editlink</edit></Survey>
但是,我想将父节点添加到编辑节点,以便生成的xml为:
<Survey><links><edit>http://example.com/editlink</edit></links></Survey>
有没有办法只使用序列化属性,而不修改类的结构?
答案 0 :(得分:2)
你不能使用那种结构。如果您将EditLink
公开为集合,那么您可以:
public class Survey
{
[XmlArray("links")]
[XmlArrayItem("edit")]
public string[] edit
{
get
{
return new [] {EditLink};
}
set
{
EditLink = value[0];
}
}
[XmlIgnore]
public string EditLink { get; set; }
}
哪个收益率:
<Survey>
<links>
<edit>http://example.com/editlink</edit>
</links>
</Survey>
答案 1 :(得分:0)
您可以尝试使用XMLSerializer class.
public class Survey
{
public string EditLink { get; set; }
}
private void SerializeSurvey()
{
XmlSerializer serializer = new XmlSerializer(typeof(Survey));
Survey survey = new Survey(){EditLink=""};
// Create an XmlTextWriter using a FileStream.
Stream fs = new FileStream(filename, FileMode.Create);
XmlWriter writer = new XmlTextWriter(fs, Encoding.Unicode);
// Serialize using the XmlTextWriter.
serializer.Serialize(writer, survey);
writer.Close();
}