Java - 检索第二个元素xml-document - DOM

时间:2015-05-27 19:36:36

标签: java xml dom

如何在以下xml-doc

中检索color-element及其属性
 <drawingobject>
    <oval x="240" y="325" width="15" height="15" filled="yes">
        <color r="0" g="255" b="255"></color>
    </oval>
</drawingobject>

并且dtd看起来像椭圆

 <!-- elementet oval -->
<!ELEMENT oval (color?)>
<!ATTLIST oval x CDATA #REQUIRED>
<!ATTLIST oval y CDATA #REQUIRED>
<!ATTLIST oval width CDATA #REQUIRED>
<!ATTLIST oval height CDATA #REQUIRED>
<!ATTLIST oval filled (yes | no) "no">

我可以检索元素“oval”及其属性,但不知道如何测试它是否包含color-element和IF - 检索它。

这是代码

 private void parse() throws Exception {

    String docName = System.getProperty("user.home") + "/Desktop/" + "myxml.xml";
    File file = new File(docName);
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    DocumentBuilder db = dbf.newDocumentBuilder();
    Document document = db.parse(file); 
    NodeList nodeList = document.getElementsByTagName("oval");
    oval = new int[nodeList.getLength()][5];

    for(int i= 0; i < nodeList.getLength(); i++) {

        oval[i][0] = Integer.parseInt(nodeList.item(i).getAttributes().getNamedItem("x").getNodeValue());
        oval[i][1] = Integer.parseInt(nodeList.item(i).getAttributes().getNamedItem("y").getNodeValue());
        oval[i][2] = Integer.parseInt(nodeList.item(i).getAttributes().getNamedItem("width").getNodeValue());
        oval[i][3] = Integer.parseInt(nodeList.item(i).getAttributes().getNamedItem("height").getNodeValue());

        if (nodeList.item(i).getAttributes().getNamedItem("filled").getNodeValue().equals("yes")) {
            oval[i][4] = 1;
        } else {
            oval[i][4] = 0;
        }


       Element ovalNode = (Element) nodeList.item(i);
       NodeList colorNodes = ovalNode.getElementsByTagName("color");
       if(colorNodes.getLength() > 0) {
            System.out.println(colorNodes.item(i).getNodeName()); 
       }

    }

堆栈跟踪

 java.lang.NullPointerException
at test.parse(test.java:60)
at test.<init>(test.java:28)
at test.main(test.java:17)

System.out.println(colorNodes.item(i).getNodeName()); 位于第60行

1 个答案:

答案 0 :(得分:2)

与获取oval元素的方式相同:使用Element.getElementsByTagName(String elementName)。您已经拥有要循环的oval元素,因此您只需在每个迭代元素上调用此方法:

for(int i= 0; i < nodeList.getLength(); i++) {
   ...

   Element ovalNode = (Element) nodeList.item(i);
   NodeList colorNodes = ovalNode.getElementsByTagName("color");
   if(colorNodes.getLength() > 0) {
        System.out.println(colorNodes.item(0).getNodeName());  // prints "color"
        ... // do something with the node
   }
}