[英]Serialize c# object in XML using variable content as attribute name
我有以下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>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.