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

发布于 2024-10-06 19:00:04 字数 542 浏览 0 评论 0原文

我一直在尝试找到一种使用 XmlReader/XmlWriter 编写 XML 的简单方法。我不太喜欢使用“IXmlSerialized”接口,但我对某些数据类别无选择。

不管怎样,我想做的很简单:

private MyClass myObject;
public void WriteXml(XmlWriter writer)
{
    writer.WriteObject(myObject); // <-- this method doesn't exists
}

所以,我找到了两个解决方法:

  1. 编写我自己的例程来手动编写我的对象。非常荒谬,因为 .Net 已经做到了。
  2. 使用 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:

  1. Write my own routine to write my object manually. Quite ridiculous since .Net already does it.
  2. 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

飘落散花 2024-10-13 19:00:04

经过一番尝试,我发现事情很简单。这是我正在为那些想知道如何解决我的问题的人使用的代码(类似于阅读和元素):

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

我不知道为什么我使问题复杂化,但它不能比这更简单。

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.

拒绝两难 2024-10-13 19:00:04

尝试使用 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文