如何使用 XmlWriter/XmlReader 读取/写入复杂对象
我一直在尝试找到一种使用 XmlReader/XmlWriter 编写 XML 的简单方法。我不太喜欢使用“IXmlSerialized”接口,但我对某些数据类别无选择。
不管怎样,我想做的很简单:
private MyClass myObject;
public void WriteXml(XmlWriter writer)
{
writer.WriteObject(myObject); // <-- this method doesn't exists
}
所以,我找到了两个解决方法:
- 编写我自己的例程来手动编写我的对象。非常荒谬,因为 .Net 已经做到了。
- 使用 StringWriter 创建一个新的序列化程序并使用 WriteValue(string) 方法。
我还没有测试第二个,但我认为它可能会起作用(由于 ReadValue 结果而不确定)。
然后我的问题是:我是否错过了一些重要的事情或者这是唯一的方法?或者有更好的方法来处理吗?
谢谢。
I've been trying to find an easy way to write XML using the XmlReader/XmlWriter. I don't really like using the interface "IXmlSerializable", but I've got no choice for some of my dataclass.
Anyway, what I want to do is quite simple:
private MyClass myObject;
public void WriteXml(XmlWriter writer)
{
writer.WriteObject(myObject); // <-- this method doesn't exists
}
So, I found 2 work around:
- Write my own routine to write my object manually. Quite ridiculous since .Net already does it.
- Create a new serializer using a StringWriter and use the WriteValue(string) method.
I haven't tested the second yet but I think it will probably work (not sure because of the ReadValue result).
Then my question is: Am I missing something important or is it the only way? Or is there a better way to handle that?
Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
经过一番尝试,我发现事情很简单。这是我正在为那些想知道如何解决我的问题的人使用的代码(类似于阅读和元素):
我不知道为什么我使问题复杂化,但它不能比这更简单。
After playing around, I found something quite simple. Here is the code I was playing with for those who are wondering how I fixed my problem (similar for reading and element):
I don't know why I was complicating the problem, but it cannot be more simpler than that.
尝试使用 XmlDocument 类。它使用XmlNode作为轻松编写xml的基础。您还可以序列化类,或使用 DataSet 类写出 xml,或将其读回到数据集或 XmlDocument 类型结构中。
Try using the XmlDocument class. It uses the XmlNode as the basis for easily writing out xml. You can also serialize a class, or use the DataSet class to write out xml, or read it back into a dataset or XmlDocument type structure.