将这种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)
请问一个例子吗?
答案 0 :(得分:1)
有很多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;
}