2014-10-09 57 views
0

我被卡住了,我想解析一个平铺的地图文件,并且存在一个问题。我不知道如何获得x,y,宽度,高度元素,以及如何重建此xml。我会非常感谢你的帮助。用DOM解析元素

<objectgroup name="Meter"> 
    <object type="meter" x="3232" y="6016" width="512" height="96"> 
    <properties> 
    <property name="id" value="1"/> 
    </properties> 
    </object> 

我的Java源代码:

public void readXml() throws ParserConfigurationException{ 
    File fXmlFile = new File("xml1.xml"); 
    DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); 
    DocumentBuilder dBuilder = dbFactory.newDocumentBuilder(); 
    Document doc = null; 

    try { 
     doc = dBuilder.parse(fXmlFile); 
    } catch (SAXException e) { 
     // TODO Auto-generated catch block 
     e.printStackTrace(); 
    } catch (IOException e) { 
     // TODO Auto-generated catch block 
     e.printStackTrace(); 
    } 

    doc.getDocumentElement().normalize(); 
System.out.println(doc.toString()); 
    System.out.println("Root element :" + doc.getDocumentElement().getNodeName()); 

    NodeList nList = doc.getElementsByTagName("objectgroup"); 

    System.out.println("----------------------------"); 

    for (int temp = 0; temp < nList.getLength(); temp++) { 

     Node nNode = nList.item(temp); 
       System.out.println("\nCurrent Element :" + nNode.getNodeName()); 

     System.out.println("\nCurrent Element :" + nNode.getAttributes().getNamedItem("meter")); 


    }} 

回答

0

你必须做出一些调整,首先你必须遍历所有孩子的,并得到所有的对象元件,然后让它们的属性值,我知道这不是一个最佳的解决方案,但会得到你所需要的:

System.out.println("Root element :" 
      + doc.getDocumentElement().getNodeName()); 

    NodeList nList = doc.getElementsByTagName("objectgroup"); 

    System.out.println("----------------------------"); 

    for (int temp = 0; temp < nList.getLength(); temp++) { 
     // for that will go for all objectGroups 
     Node nNode = nList.item(temp); 
     NodeList childs = nNode.getChildNodes(); 
     for (int i = 0; i < childs.getLength(); i++) { 
      Node child = childs.item(i); 
      if (child.getNodeName().equals("object")) { 
       // check if we are evaluating an <object> element 
       System.out.println("\nCurrent Element :" 
         + child.getNodeName()); 
       NamedNodeMap attrs = child.getAttributes(); 
       Node x = attrs.item(3), y = attrs.item(4), height = attrs 
         .item(0), width = attrs.item(2), type = attrs 
         .item(1); 
       System.out.println("\n x :" + x.getNodeValue() + " | y : " 
         + y.getNodeValue() + " | height: " 
         + height.getNodeValue() + " | width: " 
         + width.getNodeValue()); 
      } 
     } 
    }