【发布时间】:2016-06-29 18:31:10
【问题描述】:
我正在使用 XmlSerializer 序列化/反序列化复杂对象。一个属性包含一个 XML 字符串,应将其写入字符串属性而无需反序列化。
示例(可在 LinqPad 中执行):
[XmlRoot("RootObject")]
[Serializable]
public class RootClass
{
[XmlArray("SubObjects")]
[XmlArrayItem("SubObject")]
public SubClass[] SubObjecs { get; set;}
}
[Serializable]
public class SubClass
{
[XmlElement("XmlConfiguration")]
public string XmlConfiguration { get; set;}
}
void Main()
{
var obj = new RootClass()
{
SubObjecs = new[]
{
new SubClass { XmlConfiguration = "<ConfigurationX>SomeConfiguration1</ConfigurationX>" },
new SubClass { XmlConfiguration = "<ConfigurationY>SomeConfiguration2</ConfigurationY>" }
}
};
var serializer = new XmlSerializer(typeof(RootClass));
using (var stream = new MemoryStream())
{
serializer.Serialize(stream, obj);
stream.Position = 0;
Console.WriteLine(Encoding.UTF8.GetString(stream.GetBuffer()));
}
}
例子的输出是:
<?xml version="1.0"?>
<RootObject xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<SubObjects>
<SubObject>
<XmlConfiguration><ConfigurationX>SomeConfiguration1</ConfigurationX></XmlConfiguration>
</SubObject>
<SubObject>
<XmlConfiguration><ConfigurationY>SomeConfiguration2</ConfigurationY></XmlConfiguration>
</SubObject>
</SubObjects>
</RootObject>
XML 是有时以编程方式编写的配置文件,但主要由人编写/修改。因此XmlConfiguration 中的 XML 不应包含转义字符。
问题: 是否可以防止 XmlSerializer 转义 '' 字符?如果没有,是否有另一个可以使用的序列化程序?
一个有效的选项是XmlWriter.WriteRaw。但是,如果可能的话,我会避免这种不可靠且不易维护的解决方案。
我在这里发现了一个类似的问题:How to prevent XmlSerializer from escaping < and > characters。但这个问题与 !CDATA[[Content]] 有关,对我的问题没有答案。
【问题讨论】:
-
您可以在嵌套的
XmlConfiguration类上使用[XmlAnyElement]和[XmlAnyAttribute]。见XML Serialization - Leaving part of the XML as an XmlElement。 -
顺便说一下,如果您更喜欢 LINQ-to-XML 而不是旧的
XmlDocument,那么List<XElement>将与XmlAnyElement一起使用(尽管List<XAttribute>将与[XmlAnyAttribute]一起使用,奇怪。)例如见Deserialize dynamic XML。 -
@dbc:很好,谢谢!也可以将
[XmlAnyElement]与XElement结合使用(没有列表)。你想写你的 cmets 作为答案吗?
标签: c# xml escaping xml-serialization xmlserializer