[英]Parsing XML to a Java object, clarification needed
What would be the best way to stick this XML into an object? 将XML粘贴到对象中的最佳方法是什么?
<root>
<data value=1>
<cell a='1' b='0'/>
<cell a='2' b='0'/>
<cell a='3' b='0'/>
</data>
<data value=12>
<cell a='2' b='0'/>
<cell a='4' b='1'/>
<cell a='3' b='0'/>
</data>
</root>
We can assume that 我们可以假设
data value
will be unique. 每个data value
都是唯一的。 Is it possible to put this into Map<Integer, List<Cell>>
, grouping cells under the data value
? 是否可以将其放入Map<Integer, List<Cell>>
,对data value
下的单元格进行分组?
Ideally method signature would look as follows public static Map<Integer, List<Cell>> parse(String pathToFile)
理想情况下,方法签名应如下所示: public static Map<Integer, List<Cell>> parse(String pathToFile)
Would you provide an example please? 请提供一个例子吗?
There are lots of examples of XML parsing. 有很多XML解析的示例。 The simplest API (definitely not the most efficient) is DOM parsing. 最简单的API(肯定不是最有效的)是DOM解析。 Here's one way: 这是一种方法:
public static Map<Integer, List<Cell>> parse(String pathToFile) {
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(pathToFile);
Map<Integer, List<Cell>> result = new HashMap<>();
NodeList dataNodes = doc.getElementsByTagName("data");
int count = dataNodes.getLength();
for (int i = 0; i < count; ++i) {
Node node = dataNodes.item(i);
if (node.getNodeType() == Node.ELEMENT_NODE) {
Element element = (Element) node;
int value = Integer.parseInt(element.getAttribute("value"));
result.put(value, getCells(element);
}
}
return result;
}
private static List<Cell> getCells(Element dataNode) {
List<Cell> result = new ArrayList<>();
NodeList dataNodes = dataNode.getElementsByTagName("cell");
int count = dataNodes.getLength();
for (int i = 0; i < count; ++i) {
// similar to above code
}
return result;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.