我正在尝试使用 Java 中的 DOM 读取 XML
<?xml version="1.0"?>
<record>
<user>
<name>Leo</name>
<email>****@****.com</email>
<food-list>
<food>Hamburgers</food>
<food>Fish</food>
</food-list>
</user>
</record>
我目前的解决方案是
for (int userNumber = 0; userNumber < masterList.getLength(); userNumber++) {
Node singleUserEntry = masterList.item(userNumber);
if (singleUserEntry.getNodeType() == Node.ELEMENT_NODE) {
org.w3c.dom.Element userEntryElement = (org.w3c.dom.Element) singleUserEntry;
System.out.println("name : " + getTagValue("name", userEntryElement));
System.out.println("email : " +getTagValue("email", userEntryElement));
NodeList foodList = userEntryElement.getElementsByTagName("food-list").item(0).getChildNodes();
for(int i = 0; i < foodList.getLength(); i++){
Node foodNode = foodList.item(i);
System.out.println("food : " + foodNode.getNodeValue());
}
private static String getTagValue(String sTag, org.w3c.dom.Element eElement) {
NodeList nlList = eElement.getElementsByTagName(sTag).item(0).getChildNodes();
Node nValue = (Node) nlList.item(0);
return nValue.getNodeValue();
现在的输出是
name : Leo
email : ******@*****.com
food :
food : null
food :
food : null
food :
这让我很困惑。你能告诉我哪里错了吗?食物标签的数量不是预先定义的。