序列化对象时省略 XML 处理指令
我正在 C# VS2003 / .Net 1.1 应用程序中序列化一个对象。 但是,我需要在没有处理指令的情况下对其进行序列化。 XmlSerializer 类输出如下内容:
<?xml version="1.0" encoding="utf-16" ?>
<MyObject>
<Property1>Data</Property1>
<Property2>More Data</Property2>
</MyObject>
有没有办法获得类似以下内容,而不处理结果文本以删除标记?
<MyObject>
<Property1>Data</Property1>
<Property2>More Data</Property2>
</MyObject>
对于那些好奇的人,我的代码如下所示......
XmlSerializer serializer = new XmlSerializer(typeof(MyObject));
StringBuilder builder = new StringBuilder();
using ( TextWriter stringWriter = new StringWriter(builder) )
{
serializer.Serialize(stringWriter, comments);
return builder.ToString();
}
I'm serializing an object in a C# VS2003 / .Net 1.1 application. I need it serialized without the processing instruction, however. The XmlSerializer class puts out something like this:
<?xml version="1.0" encoding="utf-16" ?>
<MyObject>
<Property1>Data</Property1>
<Property2>More Data</Property2>
</MyObject>
Is there any way to get something like the following, without processing the resulting text to remove the tag?
<MyObject>
<Property1>Data</Property1>
<Property2>More Data</Property2>
</MyObject>
For those that are curious, my code looks like this...
XmlSerializer serializer = new XmlSerializer(typeof(MyObject));
StringBuilder builder = new StringBuilder();
using ( TextWriter stringWriter = new StringWriter(builder) )
{
serializer.Serialize(stringWriter, comments);
return builder.ToString();
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
在 2.0 中,您可以使用 XmLWriterSettings.OmitXmlDeclaration ,并序列化为 XmlWriter - 但我认为 1.1 中不存在这种情况; 所以并不是完全有用 - 但只是多了一个“考虑升级”的事情......是的,我意识到这并不总是可能的。
In 2.0, you would use XmLWriterSettings.OmitXmlDeclaration, and serialize to an XmlWriter - however I don't think this exists in 1.1; so not entirely useful - but just one more "consider upgrading" thing... and yes, I realise it isn't always possible.
我做了一个小修正
I made a small correction
以下链接将带您到一篇文章,其中有人提供了一种通过使用 XmlWriter 来抑制处理指令并进入“元素”状态而不是“开始”状态的方法。 这会导致处理指令无法写入。
抑制处理指令< /a>
The following link will take you to a post where someone has a method of supressing the processing instruction by using an XmlWriter and getting into an 'Element' state rather than a 'Start' state. This causes the processing instruction to not be written.
Suppress Processing Instruction
省略命名空间怎么样?
而不是使用
ex:
What about omitting namespaces ?
instead of using
ex:
这适用于 .NET 1.1。 (但你还是应该考虑升级)
This works in .NET 1.1. (But you should still consider upgrading)
如果“处理指令”指的是 xml 声明,那么您可以通过设置 XmlWriterSettings 的 OmitXmlDeclaration 属性来避免这种情况。 您需要使用 XmlWriter 进行序列化才能完成此任务。
但是啊,这并不能回答你关于 1.1 的问题。 嗯,供其他人参考。
If by "processing instruction" you mean the xml declaration, then you can avoid this by setting the OmitXmlDeclaration property of XmlWriterSettings. You'll need to serialize using an XmlWriter, to accomplish this.
But ah, this doesn't answer your question for 1.1. Well, for reference to others.