在C#中序列化XML片段 [英] Serializing an XML fragment in C#
问题描述
我想要一种将通用对象序列化为XML片段的方法。
片段将被插入到其他XML文档中,因此,我需要一个结果看起来像这样:
I want a way to serialise generic objects into XML fragments.
The fragments will be inserted into other XML documents and as such, I require a result that would look something like:
<firstProperty>firstPropertyValue</firstProperty>
<secondProperty>secondPropertyValue</secondProperty>
而不是:
as opposed to:
<className xlmns="Whatever">
<firstProperty>firstPropertyValue</firstProperty>
<secondProperty>secondPropertyValue</secondProperty>
</className>
我的代码看起来像这样:
My code looks like this:
private static string GetRow<T>(object _data)
{
StringBuilder xml = new StringBuilder();
T data = (T)_data;
XmlWriterSettings settings = new XmlWriterSettings();
settings.OmitXmlDeclaration = true;
settings.ConformanceLevel = ConformanceLevel.Fragment;
XmlSerializer serialiser = new XmlSerializer(typeof(T));
XmlWriter writer = XmlWriter.Create(xml, settings);
serialiser.Serialize(writer, data, null);
return xml.ToString();
}
我首先想到的是OmitXmlDeclaration设置可以完成这项工作 - 除非您将ConformanceLevel设置为Fragment。问题是,一旦我设置了ConformanceLevel,我就会收到以下运行时错误:
My first thought was that the OmitXmlDeclaration setting would do the job - it doesn't unless you set ConformanceLevel to Fragment. The problem is, once I do set the ConformanceLevel, I get the following run-time error:
"
无法在使用ConformanceLevel.Fragment创建的编写器上调用WriteStartDocument。
"WriteStartDocument cannot be called on writers created with ConformanceLevel.Fragment."
因此它会显示为XmlSerializer。无论ConformanceLevel被设置为Fragment而不是Document,Serialize()都调用WriteStartDocument。
我怀疑最简单的方法就是编写我自己的序列化器但是我有兴趣知道是否实际上有一种方法可以从XmlSerializer类成功生成片段。
So it would appear that XmlSerializer.Serialize() is calling WriteStartDocument regardless of ConformanceLevel being set to Fragment rather than Document.
I suspect that the easiest way around this will be to write my own serialiser but I'd be interested to know if there is actually a way of successfully producing a fragment from the XmlSerializer class.
推荐答案
如果您的问题只是为了获取片段。这样做的方法是:
var reader = XmlReader.Create(YOUR_SERIALIZED_FILE_NAME);
reader.Read();
reader.ReadToFollowing(NODE_NAME);
然后使用reader.ReadOu terXml()或reader.ReadInnerXml()根据你的要求。
希望这会有所帮助。
If your issue is just to get the fragment. One way of doing this is:
var reader = XmlReader.Create(YOUR_SERIALIZED_FILE_NAME);
reader.Read();
reader.ReadToFollowing(NODE_NAME);
Then use either reader.ReadOuterXml() or reader.ReadInnerXml() as per ur requirement.
Hope this would help.
这篇关于在C#中序列化XML片段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!