0
    <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();
  }

}

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

4

1 回答 1

1

这是问题所在:

您的<ExtendedData>标签是节点的第 4 个子节点,<Placemark>并且您只遍历标签子节点,例如节点,并且通过getTagValue,您将获得第一个孙子节点。

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

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

于 2012-10-20T05:38:10.810 回答