0

我正在尝试使用下面发布的 Java 代码显示“x”的值,但它什么也没显示。请让我知道我的错误在哪里:

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>
4

2 回答 2

4
  if(eElement.getAttribute("place") != null){

据我了解XML,“地点”不是一个属性

if (nNode.getNodeType() == Node.ELEMENT_NODE) {
   Element eElement = (Element) nNode;
   if ("place".equalsIgnoreCase(eElement.getTagName())){
      System.out.println("x: " +     eElement.getAttribute("x"));    
   }
}
于 2013-04-24T09:19:16.420 回答
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"));
      }
    }
  }
}
于 2013-04-24T09:42:02.317 回答