Java中的DOM解析器,具有属性和标记值

时间:2012-10-20 05:07:20

标签: java parsing dom

    <Document>
    <Folder>
        <Placemark id="kml_1">
            <name>$1.00 / hr 2hr time limit</name>
            <snippet> </snippet>
            <styleUrl>#ParkingMeterStyler_KMLStyler</styleUrl>
            <ExtendedData>
                <SchemaData schemaUrl="#Meter_Rates_and_Time_Limits">
                    <SimpleData name="RATE">$1.00</SimpleData>
                    <SimpleData name="LIMIT">2hr</SimpleData>
                </SchemaData>
            </ExtendedData>
            <LineString>
                <coordinates>-123.100739208611,49.2630169018194,0 -123.100348847572,49.2630078055425,0 </coordinates>
            </LineString>
        </Placemark>
</Folder>
</Document>

我无法提取“$ 1.00”和“2hr”:

<SimpleData name="RATE">$1.00</SimpleData>
<SimpleData name="LIMIT">2hr</SimpleData>

到目前为止,我的代码看起来像这样并成功提取“名称”和“坐标”:

public class Debuger {

    public static void main(String argv[]) {

      try {

        File fXmlFile = new File("parkingMeter.xml");
        DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
        Document doc = dBuilder.parse(fXmlFile);
        doc.getDocumentElement().normalize();

        System.out.println("Root element :" + doc.getDocumentElement().getNodeName());
        NodeList nList = doc.getElementsByTagName("Placemark");
        System.out.println("-----------------------");

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

           Node nNode = nList.item(temp);
           if (nNode.getNodeType() == Node.ELEMENT_NODE) {

              Element eElement = (Element) nNode;

              System.out.println("Name : " + getTagValue("name", eElement));

              if(eElement.getAttribute("name").equals("RATE")){
                  System.out.println("Rate : " + getTagValue("SimpleData", eElement));
              }else if(eElement.getAttribute("name").equals("LIMIT")) {
                   System.out.println("Limit : " + getTagValue("SimpleData", eElement));
                }

              System.out.println("Coordinates : " + getTagValue("coordinates", eElement));

           }
        }
      } catch (Exception e) {
        e.printStackTrace();
      }
  }

  private static String getTagValue(String sTag, Element eElement) {
    NodeList nlList = eElement.getElementsByTagName(sTag).item(0).getChildNodes();

        Node nValue = (Node) nlList.item(0);

    return nValue.getNodeValue();
  }

}

我真的被困在这里,非常感谢帮助。

1 个答案:

答案 0 :(得分:1)

问题在于:

您的<ExtendedData>标记是<Placemark>节点的第4个子节点,并且您只是遍历标记子节点,例如节点并通过getTagValue,你将成为第一个大孩子。

   NodeList nlList = eElement.getElementsByTagName(sTag).item(0).getChildNodes();

请通过迭代节点的子节点来更正遍历。它应该工作。