Noob在这里。我正在尝试使用DOM读取xml文件到Java,从不同的对象导入数据。由于元素是嵌套的,因此我尝试获取每个子孙信息,而我看不到孙信息。
这是文件的示例
<?xml version="1.0" encoding="UTF-8"?>
<AAAA>
<BBBB>
<CCC>text</CCC>
<DDD>
<a>value</a>
<b>value</b>
<c>value</c>
</DDD>
<EEE>
<aa>
<a>text</a>
<b>
<a>value</a>
<b>value</b>
<c>value</c>
</b>
</aa>
<bb>
<a>text</a>
<b>
<a>value</a>
<b>value</b>
<c>value</c>
</b>
</bb>
</EEE>
</BBBB>
</AAAA>
我可以到达节点,但不能到达以下节点。
这是我到目前为止的代码的一部分:
@SuppressWarnings("unchecked")
public static List<BBBB> readXMLFileToList(File file) {
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
dbFactory.setIgnoringElementContentWhitespace(true);
dbFactory.setNamespaceAware(true);
DocumentBuilder dBuilder;
List<BBBB> list = new ArrayList<>();
try {
dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(file);
doc.getDocumentElement().normalize();
NodeList nodeList = doc.getElementsByTagName("AAAA");
for (int i = 0; i < nodeList.getLength(); i++) {
list.add(getBBBB(nodeList.item(i)));
}
} catch (SAXException | ParserConfigurationException | IOException e1) {
e1.printStackTrace();
}
return list;
}
private static BBBB getBBBB (Node node) {
BBBB bbbb = null;
if (node.getNodeType() == Node.ELEMENT_NODE) {
Element element = (Element) node;
String ccc = getTagValue("CCC", element);
if (dddNode.getNodeName().trim().equals("#text")) {
dddNode = element.getFirstChild().getNextSibling();
}
DDD ddd = getDDD(dddNode);
bbbb = new BBBB (ccc, ddd);
}
return bbbb;
}
private static DDD getDDD(Node node) {
Element element = (Element) node;
Double a = Double.parseDouble(getTagValue("a", element));
Double b = Double.parseDouble(getTagValue("b", element));
Double c = Double.parseDouble(getTagValue("c", element));
DDD ddd = new DDD (a,b,c);
return ddd;
}