And*_*uiz 8 java xml xstream xml-parsing
我正在使用xStream来操作XML.一切都好.要放置XML存档和其他东西.但是,我有一个问题:
示例:我的xml包含一个标记,在这个标记中,我有一些名为的标记<comment>.看一个示例代码:
<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>
Run Code Online (Sandbox Code Playgroud)
并且渐进地.我可以在标签内做500个标签.这些评论属于评论类型.
如何使用xStream序列化以将所有这些标记放入类中?我不怎么在课堂上让它接收各种物品.
显然,我将使用数组或其他方法.但我不知道怎么做到这一点.
Rob*_*ska 12
对于该XML,您可能希望拥有类结构,如:
public class Comment {
long id
String desc
}
public class Comments {
List<Comment> comments = new ArrayList<Comment>();
}
Run Code Online (Sandbox Code Playgroud)
你的解组逻辑就像这样:
XStream xstream = new XStream();
xstream.alias("comments", Comments.class);
xstream.alias("comment", Comment.class);
xstream.addImplicitCollection(Comments.class, "comments");
Comments comments = (Comments)xstream.fromXML(xml);
Run Code Online (Sandbox Code Playgroud)
另外,正如Nishan在评论中提到的那样,你的XML形成不正确.你需要确保你的<comment>结束</comment>与否</comments>.在此答案中的任何代码都可行之前,您需要解决此问题.
虽然它是一个旧线程,但这里是Annotated版本:
@XStreamAlias("comment")
public class Comment {
long id
String desc
}
@XStreamAlias("comments")
public class Comments {
@XStreamImplicit(itemFieldName = "comment")
List<Comment> comments;
}
Run Code Online (Sandbox Code Playgroud)
解散你需要这个:
XStream xStream = new XStream();
xStream.processAnnotations(new Class[] { Comments.class, Comment.class });
Comments comments = (Comments)xStream.fromXML(xml);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
9396 次 |
| 最近记录: |