部分XML序列化/反序列化 [英] partial xml serialization/deserialization
问题描述
有可能部分地(DE)/从/对象序列化到一个字符串?
is it possible to partially (de)/serialize an object from/into a string?
class Foo
{
Bar Bar{get;set;}
string XmlJunkAsString{get;set;}
}
所以ultmately,我们希望下面的字符串工作...
so ultmately, we would want the string below to work...
<Foo><Bar></Bar><XmlJunkAsString><xml><that/><will/><not/><be/><parsed/></xml></XmlJunkAsString></Foo>
和最终我们可以找到Foo.XmlJunkAsString的内容包含字符串
and ultimately we could find the contents of Foo.XmlJunkAsString to contain the string
<xml><that/><will/><not/><be/><parsed/></xml>
和反之亦然会发生在哪里以上,就可以产生的XML时美孚的这一特定实例被序列化
and vice-versa would occur where the xml above would be generated when this particular instance of Foo is serialized.
可能吗?
推荐答案
我希望 [XMLTEXT]
会的工作,但它似乎变得逃脱;你可以实现的IXmlSerializable
,但是这是非常棘手的。以下是难看,但给出正确的结果(虽然你可能会得到一些XML空白差异)
I was hoping that [XmlText]
would work, but it seems to get escaped; you could implement IXmlSerializable
, but that is very tricky. The following is ugly, but gives the right result (although you might get some xml whitespace differences)
using System;
using System.ComponentModel;
using System.Xml;
using System.Xml.Serialization;
public class Bar { }
public class Foo
{
public Bar Bar { get; set; }
[XmlIgnore]
public string XmlJunkAsString { get; set; }
[XmlElement("XmlJunkAsString"), Browsable(false)]
[EditorBrowsable(EditorBrowsableState.Never)]
public XmlElement XmlJunkAsStringSerialized
{
get
{
string xml = XmlJunkAsString;
if (string.IsNullOrEmpty(xml)) return null;
XmlDocument doc = new XmlDocument();
doc.LoadXml(xml);
return doc.DocumentElement;
}
set
{
XmlJunkAsString = value == null ? null : value.OuterXml;
}
}
}
static class Program {
static void Main()
{
var obj = new Foo
{
Bar = new Bar(),
XmlJunkAsString = "<xml><that/><will/><not/><be/><parsed/></xml>"
};
var ser = new XmlSerializer(obj.GetType());
ser.Serialize(Console.Out, obj);
}
}
这篇关于部分XML序列化/反序列化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!