简体   繁体   English

简单的Xml列表解析问题

[英]Simple Xml list parsing problem

I have this xml: 我有这个xml:

<root>
<fruitlist>
    <apple>4</apple>
    <apple>5</apple>
    <orange>2</orange>
    <orange>6</orange>
</fruitlist>
</root>

I'm writing a parser class, although I can't figure out how to deal with multiple node types. 我正在编写一个解析器类,尽管我不知道如何处理多种节点类型。 I can easily parse a list that contains only one node type (eg. just apples, not oranges) 我可以轻松地解析仅包含一种节点类型的列表(例如,仅苹果而不是橘子)

@ElementList(name = "fruitlist")
private List<Apple> exercises;

with more than one node type it also wants so parse non Apple nodes which doesn't work. 具有多个节点类型的节点,它还希望解析非Apple节点,这是行不通的。 I also tried to make another list for oranges, but it doen't work, I can't use fruitlist name more than once. 我还尝试为橙子创建另一个列表,但是它不起作用,我不能多次使用水果列表名称。

@ElementList(name = "fruitlist", entry = "orange")
private List<Orange> exercises;

The ideal would be two seperate list for both node types. 对于两种节点类型,理想的情况是使用两个单独的列表。

Hubi 湖北

EDIT: After more searching & fiddling this question is a duplicate: 编辑:经过更多的搜索和摆弄这个问题是重复的:

Inheritance with Simple XML Framework 简单XML框架的继承

Try this, it will work. 试试这个,它将起作用。

@ElementListUnion({
   @ElementList(entry="apple", type=Apple.class),
   @ElementList(entry="orange", type=Orange.class)
})
private List<Fruit> fruitlist;

The ideal data structure to solve this parsing problem would probably be an HashTable with the name of the element as key (String) and the list of his possible child as content (List 解决此解析问题的理想数据结构可能是HashTable ,其元素名称为键(String),其可能子级的列表为content(List

Hashtable<String, Integer> numbers = new Hashtable<String, List<String>>();

Anyway if you wanna parse an XML file there are lots of possible framworks you can use in Java. 无论如何,如果您想解析XML文件,可以在Java中使用很多可能的framworks。

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

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