使用变量内容作为属性名称在 XML 中序列化 c# 对象
本文关键字:XML 序列化 对象 属性 变量 | 更新日期: 2023-09-27 18:32:25
我有以下 c# 对象:
class Modification {
public string Name;
public string Value;
}
我想使用序列化程序按以下方式序列化我的对象:
<name>value</name>
示例:假设我们将这些变量设置为
Name = "Autoroute"
Value = 53
我希望 xml 看起来像:
<test>
<Autoroute>53</Autoroute>
</test>
我在某处看到序列化程序不支持此功能,但是有没有办法重载序列化程序以允许这种行为?
更改 XML 结构不是一种选择,因为它已经是一种约定。
您可以使用
IXmlSerializable
来执行此操作,尽管这并不能让您控制根元素名称 - 您必须在序列化程序中设置它(当您将其作为更大的 xml 结构的一部分读取时,这可能会带来其他挑战......
public class Modification : IXmlSerializable
{
public string Name;
public string Value;
public System.Xml.Schema.XmlSchema GetSchema()
{
return null;
}
public void ReadXml(System.Xml.XmlReader reader)
{
reader.ReadStartElement();
Name = reader.Name;
Value = reader.ReadElementContentAsString();
reader.ReadEndElement();
}
public void WriteXml(System.Xml.XmlWriter writer)
{
writer.WriteElementString(Name, Value);
}
}
用法
Modification modification = new Modification()
{
Name = "Autoroute",
Value = "53"
};
Modification andBack = null;
string rootElement = "test";
XmlSerializer s = new XmlSerializer(typeof(Modification), new XmlRootAttribute(rootElement));
using (StreamWriter writer = new StreamWriter(@"c:'temp'output.xml"))
s.Serialize(writer, modification);
using (StreamReader reader = new StreamReader(@"c:'temp'output.xml"))
andBack = s.Deserialize(reader) as Modification;
Console.WriteLine("{0}={1}", andBack.Name, andBack.Value);
由此生成的 XML 如下所示,
<?xml version="1.0" encoding="utf-8"?>
<test>
<Autoroute>53</Autoroute>
</test>