[英]Parsing XML to a Java object, clarification needed
将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>
我们可以假设
data value
都是唯一的。 是否可以将其放入Map<Integer, List<Cell>>
,对data value
下的单元格进行分组?
理想情况下,方法签名应如下所示: public static Map<Integer, List<Cell>> parse(String pathToFile)
请提供一个例子吗?
有很多XML解析的示例。 最简单的API(肯定不是最有效的)是DOM解析。 这是一种方法:
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.