如何解析XML数据

时间:2014-05-02 16:39:59

标签: java xml

我有一个XML,就像

<polygon>
<coordinates>
<coordinate order="1" long="75.9375" lat="32.91648534731439"/>
<coordinate order="2" long="76.640625" lat="23.241346102386135"/>
<coordinate order="3" long="88.59375" lat="31.052933985705163"/>
</coordinates>
</polygon>

我想获取每个坐标的long和lat值并分配给string。 我当时想:

DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
                    DocumentBuilder db = dbf.newDocumentBuilder();

                    Document document = db.parse( new InputSource(new StringReader(s)));
                    System.out.println(document.getChildNodes());

                    NodeList nl = document.getElementsByTagName("coordinates");
                    for (int i = 0; i < nl.getLength(); i++)
                    {
                      System.out.println("name is : "+nl.item(i).getNodeName());
                      System.out.println("name is : "+nl.item(i).getNodeValue());


                    }

String reader是我传递的XML String,但我无法获取数据。

2 个答案:

答案 0 :(得分:2)

您需要将每个Node投放到Element,并且您需要确保获得正确的元素。

for(int i = 0; i < nl.getLength(); i++) {
    Element e = (Element)nl.item(i);

    String lat = e.getAttribute("lat");

    String longStr = e.getAttribute("long");
}

答案 1 :(得分:0)

根据您的层次结构创建NodeList ,如下所示。到达childNode后,开始使用Element迭代nodelist,并尝试使用 elementObject.getAttribute(&#34; tagname&#34;)获取属性值。

XML结构:

多边形 - &gt;坐标 - &gt;坐标 - &gt;属性 - lat和long

NodeList valueList = doc.getElementsByTagName("polygon");
for (int i = 0; i < valueList.getLength(); ++i)
{
    Element labTest = (Element) valueList .item(i);
    String labTestType = labTest.getAttribute("type");

    NodeList coordinates= labTest.getElementsByTagName("coordinates");
    for (int j = 0; j < coordinates.getLength(); ++j)
    {
        Element value = (Element) coordinates.item(j);
        String valueType = value.getAttribute("type");

        NodeList coordinate= value.getElementsByTagName("coordinate");
        for (int k = 0; k < coordinate.getLength(); ++k)
        {
            Element condition = (Element) coordinate.item(k);
            String lat = e.getAttribute("lat");

            String long = e.getAttribute("long");
        }
    }
}