我试图显示" x"的值使用下面发布的Java代码,但它什么也没显示。请让我知道我的错误在哪里:
Java代码:
for (int temp = 0; temp < nList.getLength(); temp++) {
Node nNode = nList.item(temp);
System.out.println("\nCurrent Element :" + nNode.getNodeName());
System.out.println("\n"+nList.getLength());
if (nNode.getNodeType() == Node.ELEMENT_NODE) {
Element eElement = (Element) nNode;
if(eElement.getAttribute("place") != null){
System.out.println("x: " + eElement.getElementsByTagName("place").item(0).getTextContent());
}
}
}
XML文件:
<?xml version="1.0" encoding="UTF-8"?>
<document>
<group id="Fontanestra">
<place x="4222873.962227057" y="2902240.7064015563" class="hdlamp lamp651
Fontanestra"/>
<place x="4222675.856667058" y="2902341.1436763224" class="hdlamp lamp745
Fontanestra"/>
<place x="4222761.571650493" y="2902285.145924819" class="hdlamp lamp871
Fontanestra"/>
<place x="4222703.30618614" y="2902320.7303823503" class="hdlamp lamp972
Fontanestra"/>
<place x="4222802.65477977" y="2902265.5807657656" class="hdlamp lamp1084
Fontanestra"/>
<place x="4222935.246730494" y="2902220.7360558496" class="hdlamp lamp1110
Fontanestra"/>
<place x="4222734.639113373" y="2902300.2547685634" class="hdlamp lamp1215
Fontanestra"/>
<place x="4222837.368032" y="2902252.747460649" class="hdlamp
lamp1225 Fontanestra"/>
<place x="4222904.859771981" y="2902230.8135758354" class="hdlamp lamp1336
Fontanestra"/>
</group>
</document>
答案 0 :(得分:4)
if(eElement.getAttribute("place") != null){
据我所知,XML“place”不是属性
if (nNode.getNodeType() == Node.ELEMENT_NODE) {
Element eElement = (Element) nNode;
if ("place".equalsIgnoreCase(eElement.getTagName())){
System.out.println("x: " + eElement.getAttribute("x"));
}
}
答案 1 :(得分:0)
查看您的代码,我认为nList
是通过调用:
NodeList nList = someDocument.getElementsByTagName("group");
因此,您需要调整循环结构,再按名称搜索,而不是寻找属性:
for (int i = 0; i < nList.getLength(); i++) {
Node groupNode = nList.item(i);
NodeList placeList = groupNode.getChildNodes();
for (int j = 0; j < placeList.getLength(); j++) {
Node placeNode = placeList.item(j);
if (placeNode instanceof Element) {
Element element = (Element) placeNode;
if ("place".equalsIgnoreCase(element.getTagName())) {
System.out.println("x: " + element.getAttribute("x"));
}
}
}
}