简体   繁体   English

如何使用XmlWriter / XmlReader读取/写入复杂对象

[英]How to read/write complex object with XmlWriter/XmlReader

I've been trying to find an easy way to write XML using the XmlReader/XmlWriter. 我一直在尝试找到一种使用XmlReader / XmlWriter编写XML的简单方法。 I don't really like using the interface "IXmlSerializable", but I've got no choice for some of my dataclass. 我真的不喜欢使用“ IXmlSerializable”接口,但是我的某些数据类别无选择。

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: 因此,我发现有两种解决方法:

  1. Write my own routine to write my object manually. 编写自己的例程以手动编写对象。 Quite ridiculous since .Net already does it. 相当可笑,因为.Net已经做到了。
  2. Create a new serializer using a StringWriter and use the WriteValue(string) method. 使用StringWriter创建一个新的序列化器,并使用WriteValue(string)方法。

I haven't tested the second yet but I think it will probably work (not sure because of the ReadValue result). 我还没有测试第二个,但是我认为它可能会工作(由于ReadValue结果,所以不确定)。

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. 谢谢。

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): 这是我正在为那些想知道如何解决问题的人使用的代码(类似于阅读和元素):

    public static void WriteElement(XmlWriter writer, string name, object value)
    {
        var serializer = new XmlSerializer(value.GetType(), new XmlRootAttribute(name));
        serializer.Serialize(writer, value);
    }

I don't know why I was complicating the problem, but it cannot be more simpler than that. 我不知道为什么使问题复杂化,但是没有比这更简单的了。

Try using the XmlDocument class. 尝试使用XmlDocument类。 It uses the XmlNode as the basis for easily writing out xml. 它使用XmlNode作为轻松写出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. 您还可以序列化一个类,或使用DataSet类写出xml,或将其读回到数据集或XmlDocument类型结构中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM