问题描述
|
有没有一种方法可以强制XML序列化器将元素添加为内联而不是使用Value布局。我基本上只有一个庞大的结构列表,我想向每个启用的子元素添加一个内联元素。
<main>
<item>
<value>1</value>
<name>Alphabet</name>
</item>
...
</main>
我基本上想添加:
<item Enabled=\"true\">
如果启用了元素块。有没有办法做到这一点?
解决方法
是的,只需用property2ѭ标记Enabled属性:
[XmlAttribute(\"Enabled\")]
public bool Enabled { get; set; }
在MSDN上可以找到有关控制xml序列化的属性的文档:
http://msdn.microsoft.com/zh-cn/library/83y7df3e%28v=VS.100%29.aspx
, XmlAttributeAttribute
XmlAttributeAttribute属性允许您指定成员应序列化为属性,以及该属性的名称。由于属性只能表示单个值,因此只能将简单数据用作属性。
坍方
using System;
using System.Xml.Serialization;
namespace XmlEntities {
[XmlRoot(\"XmlDocRoot\")]
public class RootClass {
private int attribute_id;
[XmlAttribute(\"id\")]
public int Id {
get { return attribute_id; }
set { attribute_id = value; }
}
}
}
这将序列化为与此类似的东西...
坍方
<XmlDocRoot id=\"1\" />
更多信息请在SO上检查此答案:如何为C#XML序列化添加属性