简体   繁体   English

从XML元素读取属性

[英]Reading attributes from XML elements

I'm trying to display the values of "x" using the Java code posted below, but it displays nothing. 我正在尝试使用下面发布的Java代码显示“ x”的值,但是什么也不显示。 Please let me know where my mistake is: 请让我知道我的错误在哪里:

Java code: 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 file: 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>
  if(eElement.getAttribute("place") != null){

As far as I understand the XML, "place" is not an attribute 据我了解的XML,“地方”不是一个属性

if (nNode.getNodeType() == Node.ELEMENT_NODE) {
   Element eElement = (Element) nNode;
   if ("place".equalsIgnoreCase(eElement.getTagName())){
      System.out.println("x: " +     eElement.getAttribute("x"));    
   }
}

Looking at your code, I think nList was obtained by calling: 查看您的代码,我认为nList是通过调用获得的:

NodeList nList = someDocument.getElementsByTagName("group");

Therefore you will need to adjust your looping structure, plus search by name rather than seeking an attribute: 因此,您将需要调整循环结构,并按名称搜索而不是查找属性:

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"));
      }
    }
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM