Xml序列化删除内部标记
本文关键字:内部 删除 序列化 Xml | 更新日期: 2023-09-27 18:15:53
我在获得我想要的xml序列化时遇到了一点麻烦。事先感谢您的帮助。
所以,我的目标xml看起来像这样:
<ChangeSet>
<Change class="object" key="foo">
bar
</Change>
<Change class="testing" key="temp">
temp
</Change>
</ChangeSet>
我实际得到的是:
<ChangeSet>
<Change class="object" key="foo">
<Value> bar </Value>
</Change>
<Change class="testing" key="temp">
<Value> temp </Value>
</Change>
</ChangeSet>
注意,value标记内部的值需要能够是任何对象。(集合、对象、泛型类型……等)我怎样才能摆脱价值标签?
c#代码:[Serializable]
[XmlRoot("ChangeSet")]
public class ChangeSet
{
[XmlElement("Change", typeof(Change))]
public List<Change> Changes;
}
public class Change
{
[XmlAttribute("Class")]
public string Class;
[XmlAttribute("Description")]
public string Key;
public object Value;
}
StringBuilder xml = new StringBuilder();
XmlSerializer serializer = new XmlSerializer(objToSerialize.GetType());
XmlWriterSettings settings = new XmlWriterSettings()
{
OmitXmlDeclaration = true,
Indent = true
};
using (StringWriter writer = new StringWriter(xml))
{
using (XmlWriter xmlWriter = XmlWriter.Create(writer, settings))
{
XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
ns.Add("", ""); // Removes the xsd & xsi namespace declarations from the xml
serializer.Serialize(xmlWriter, objToSerialize, ns);
}
}
使用[XmlText]属性超过字符串类型的值
[XMLText]
public string Value;
或使用另一个字符串属性并忽略Value属性
[XMLIgnore]
public object Value;
[XMLText]
public string ValueString
{
get{ return this.Value.ToString(); }
}