我正在读取XML文件并显示文件的输出。
但是问题是,当一个节点有许多子节点时,会发生这种情况:
---------character
---------id
------------>148
---------name
------------>Arya Stark
---------gender
------------>Female
---------culture
------------>Northmen
---------born
------------>In 289 AC, at Winterfell
---------died
---------alive
------------>TRUE
---------titles
---------title
------------>Princess
---------aliases
---------alias
------------>Arya Horseface
---------alias
------------>Arya Underfoot
---------alias
------------>Arry
---------alias
------------>Lumpyface
---------alias
------------>Lumpyhead
---------alias
------------>Stickboy
---------alias
------------>Weasel
---------alias
------------>Nymeria
---------alias
------------>Squan
---------alias
------------>Saltb
---------alias
------------>Cat of the Canaly
---------alias
------------>Bets
---------alias
------------>The Blind Girh
---------alias
------------>The Ugly Little Girl
---------alias
------------>Mercedenl
---------alias
------------>Mercye
如您所见,别名有很多别名,我想同时输出它们。
这是我的代码:
public class JavaApplication20 {
/**
* @param args the command line arguments
*/
public static void main(String[] args) throws ParserConfigurationException, org.xml.sax.SAXException, IOException {
String path = "got.xml";
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setNamespaceAware(true);
DocumentBuilder builder = factory.newDocumentBuilder();
org.w3c.dom.Document document = builder.parse(path);
document.getDocumentElement().normalize();
iterateNodes(document.getDocumentElement());
}
private static void iterateNodes(Node node) {
NodeList nodeList = node.getChildNodes();
for (int i = 0; i < nodeList.getLength(); i++) {
Node currentode = nodeList.item(i);
if (currentode.getNodeType() == Node.ELEMENT_NODE) {
System.out.print("---------");
System.out.println(currentode.getNodeName().trim());
Element element = (Element) currentode;
iterateNodes(element);
} else if (!nodeList.item(i).getTextContent().trim().equals("")) {
System.out.println("------------>" + nodeList.item(i).getTextContent().trim());
}
}
}
}
我试图检测节点何时有许多子节点,但我不知道。
谢谢!
答案 0 :(得分:0)
我已经解决了,这是一个不好的解决方案,但是可以解决问题!
我创建了一个存储节点名的字符串,如果下一个节点的名称与字符串var相同,则id不显示名称
if(!anterior.equals(currentode.getNodeName().trim())){
System.out.print("---------");
System.out.println(currentode.getNodeName().trim());
}
anterior=currentode.getNodeName().trim();