xStream问题-如何反序列化多个对象
我正在使用 xStream 来操作 XML。一切都好。放置 XML 存档和其他东西。但是,我有一个问题:
示例:我的 xml 包含一个 tag ,在这个 tag 中,我还有一些名为
的标签。看一下示例代码:
<comments>
<comment>
<id>1</id>
<desc>A comment</desc>
</comment>
<comment>
<id>2</id>
<desc>Another comment</desc>
</comment>
<comment>
<id>3</id>
<desc>Another one comment</desc>
</comment>
</comments>
逐步进行。 我可以在标签内做500个标签。这些评论属于评论类型。
我如何使用 xStream 进行序列化以将所有这些标签放入类中?我不知道如何在类中使其接收各种对象。
显然,我将使用数组或其他数组来实现此目的。 但我不知道该怎么做。
I'm using xStream to manipulate XML. All is okay. To put on XML archive and other things. But, I have a problem:
Example: My xml contains a tag , and inside this one, I have some more tags named <comment>
. Look at a example code:
<comments>
<comment>
<id>1</id>
<desc>A comment</desc>
</comment>
<comment>
<id>2</id>
<desc>Another comment</desc>
</comment>
<comment>
<id>3</id>
<desc>Another one comment</desc>
</comment>
</comments>
And progressivelly.
I can do 500 tags inside the tag. And these comments are of type comment.
How I can do to serialize with the xStream to put all of these tags in the classes? I don't how to make in the class to it receive the various objects.
Obviously, I will make this with an Array, or some other.
But I don't know how I can do this.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
对于该 XML,您可能希望有一个类似以下的类结构:
您的解组逻辑将类似于:
另外,正如 Nishan 在评论中提到的,您的 XML 格式不正确。您需要确保您的
以结尾,而不是
。您需要先解决此问题,然后此答案中的任何代码才能工作。
For that XML, you'd probably be looking to have a class structure like:
Your unmarshalling logic would then be something like:
Additionaly, as Nishan mentioned in the comments, your XML isn't quite formed correctly. You'll need to make sure your
<comment>
ends with</comment>
and not</comments>
. You'll need to fix this before any of the code in this answer will work.虽然它是一个旧线程,但这里是带注释的版本:
要解组,您需要以下内容:
Although it is an old thread, but here is the Annotated version:
To unmarshal you need this:
如果您处理多个对象,您可能希望多次调用
fromXML
(InputStream
in) 来获取每个对象。但是,该方法不会按预期进行处理,并且如果您这样做,则会抛出一条措辞不当的异常消息。或者,将所有对象包装在较大的对象中可能会导致程序使用比所需更多的内存或耗尽内存。为了解决这个问题,我创建了一个通用实用程序方法,这样我就可以将每个小对象解析为它自己的字符串,这样我就可以使用
fromXML(String)
方法并仍然按比例放大大小。调用示例:
If your dealing with multiple objects, you might be expecting to call
fromXML
(InputStream
in) multiple times to get each object. The method does not handle as expected though and has throws a poorly worded exception message if you do this. Alternatively, wrapping all objects in a larger object may cause the program use more memory then desired or run out of memory.To fix this, I made a generic utility method so I could parse each small object into its own string so I could
fromXML(String)
method and still scale up in size.Example calls: