简体   繁体   English

从XML提取元素的属性

[英]Extract attribute of an element from XML

I am trying to extract the "ref" info for each "nd" under element "way". 我试图为元素“ way”下的每个“ nd”提取“ ref”信息。 I have tried to used regular java xml parser and XPath but still cannot figure out how to retrieve multiple child nodes. 我尝试使用常规的Java xml解析器和XPath,但仍然无法弄清楚如何检索多个子节点。

<?xml version='1.0' encoding='UTF-8'?>
<osm version="0.6" generator="Osmosis 0.43.1">
  <node id="95946773" version="3" timestamp="2009-11-14T15:52:46Z" uid="17427" user="dysteleologist" changeset="3114170" lat="26.2870135" lon="-80.2120936"/>
  <node id="95946776" version="3" timestamp="2010-10-23T15:07:03Z" uid="207745" user="NE2" changeset="6146275" lat="26.2870058" lon="-80.2128489"/>
<way id="226137459" version="1" timestamp="2013-06-17T20:19:27Z" uid="1119200" user="wagn" changeset="16595491">
    <nd ref="2349898722"/>
    <nd ref="2349898723"/>
    <nd ref="2349898724"/>
    <nd ref="2349898725"/>
    <nd ref="2349898726"/>
    <nd ref="2349898730"/>
    <nd ref="2349898727"/>
    <nd ref="2349898728"/>
    <nd ref="2349898729"/>
    <nd ref="2349898722"/>
    <tag k="building" v="house"/>
  </way>
</osm>

My code to extract the "way" element. 我的代码提取“ way”元素。

 NodeList wList = doc.getElementsByTagName("way");
for (int temp = 0; temp < wList.getLength(); temp++) {

    Node wNode = wList.item(temp);

    if (wNode.getNodeType() == Node.ELEMENT_NODE) {
        Element wElement = (Element) wNode;

        output_str = "";
        output_str += wElement.getAttribute("id")+ " ";
                      System.out.println(wElement.getElementsByTagName("nd").item(0).getAttribute("ref"));

It I change the last print line to below 我将最后一个打印行更改为以下

System.out.println(wElement.getElementsByTagName("nd").item(0).getNodeName());

It actually prints out "nd" as the node name, but I cannot get the attributes of the node. 它实际上打印出“ nd”作为节点名称,但是我无法获得该节点的属性。

In javascript, it works as below, but this syntax doesn't work in Java. 在javascript中,它的工作方式如下,但是此语法在Java中不起作用。

System.out.println(wElement.getElementsByTagName("nd")[0].getAttribute("ref"));

Thanks, 谢谢,

Tony 托尼

The below code can be used to get the values of the ref attribute and to store them in an arraylist. 以下代码可用于获取ref属性的值并将其存储在arraylist中。

String s="<?xml version='1.0' encoding='UTF-8'?><osm version=\"0.6\" generator=\"Osmosis 0.43.1\">  <node id=\"95946773\" version=\"3\" timestamp=\"2009-11-14T15:52:46Z\" uid=\"17427\" user=\"dysteleologist\" changeset=\"3114170\" lat=\"26.2870135\" lon=\"-80.2120936\"/>  <node id=\"95946776\" version=\"3\" timestamp=\"2010-10-23T15:07:03Z\" uid=\"207745\" user=\"NE2\" changeset=\"6146275\" lat=\"26.2870058\" lon=\"-80.2128489\"/><way id=\"226137459\" version=\"1\" timestamp=\"2013-06-17T20:19:27Z\" uid=\"1119200\" user=\"wagn\" changeset=\"16595491\">    <nd ref=\"2349898722\"/>    <nd ref=\"2349898723\"/>    <nd ref=\"2349898724\"/>    <nd ref=\"2349898725\"/>    <nd ref=\"2349898726\"/>    <nd ref=\"2349898730\"/>    <nd ref=\"2349898727\"/>    <nd ref=\"2349898728\"/>    <nd ref=\"2349898729\"/>    <nd ref=\"2349898722\"/>    <tag k=\"building\" v=\"house\"/>  </way></osm>";


    DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
    builderFactory.setNamespaceAware(true);
    InputSource is = new InputSource(new StringReader(s));


    DocumentBuilder builder;
    try {
        builderFactory.setIgnoringElementContentWhitespace(true);
        builder = builderFactory.newDocumentBuilder();
        Document xml = builder.parse(is);
        XPathFactory factory = javax.xml.xpath.XPathFactory.newInstance();
        XPath xPath = factory.newXPath();
        XPathExpression expression;

        expression = xPath.compile("/osm/way/nd/@ref");
        NodeList ss = (NodeList) expression.evaluate(xml,XPathConstants.NODESET);
        ArrayList<String> list = new ArrayList<String>();
        for (int i = 0; i < ss.getLength(); i++) {
            list.add(ss.item(i).getTextContent());
        }
        System.out.println(list);
    } catch (ParserConfigurationException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (SAXException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (XPathExpressionException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }   
}

this syntax doesn't work in Java. 此语法在Java中不起作用。

System.out.println(wElement.getElementsByTagName("nd")[0].getAttribute("ref"));

There are two things you need to change there. 您需要在此更改两件事。 Firstly Java uses .item(0) instead of [0] , and secondly because Java is strongly typed, and getAttribute is a method of Element rather than Node , you need a cast: 首先,Java使用.item(0)而不是[0] ;其次,因为Java是强类型的,并且getAttributeElement的方法而不是Node ,因此需要强制转换:

System.out.println(((Element)wElement.getElementsByTagName("nd").item(0))
                    .getAttribute("ref"));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM