我正在尝试序列化一个对象以满足另一个系统要求。
它需要看起来像这样:
<custom-attribute name="Colour" dt:dt="string">blue</custom-attribute>
而是看起来像这样:
<custom-attribute>blue</custom-attribute>
到目前为止我有这个:
[XmlElement("custom-attribute")]
public String Colour{ get; set; }
我不太确定实现此目标需要哪些元数据。
最佳答案
你可以实现 IXmlSerializable :
public class Root
{
[XmlElement("custom-attribute")]
public Colour Colour { get; set; }
}
public class Colour : IXmlSerializable
{
[XmlText]
public string Value { get; set; }
public XmlSchema GetSchema()
{
return null;
}
public void ReadXml(XmlReader reader)
{
throw new NotImplementedException();
}
public void WriteXml(XmlWriter writer)
{
writer.WriteAttributeString("dt:dt", "", "string");
writer.WriteAttributeString("name", "Colour");
writer.WriteString(Value);
}
}
class Program
{
static void Main()
{
var serializer = new XmlSerializer(typeof(Root));
var root = new Root
{
Colour = new Colour
{
Value = "blue"
}
};
serializer.Serialize(Console.Out, root);
}
}
关于c# - .net 中的 XML 序列化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6055140/