简体   繁体   中英

How to get value with considering tag name and its attribute in XML using Java

I'm sorry, I wanna ask about how to get tag value with considering tag name and its attribute. I use the XML for indexing on lucene

This is the XML

 <?xml version="1.0" encoding="utf-8"?>
<Root xmlns:wb="http://www.worldbank.org">
  <data>
    <record>
      <field name="Country or Area" key="ARB">Arab World</field>
      <field name="Item" key="AG.AGR.TRAC.NO">Agricultural machinery, tractors</field>
      <field name="Year">1961</field>
      <field name="Value">73480</field>
    </record>
  </data>
</Root>

In early project, I only get the tag value with source like this:

private String getTagValue(String tag, Element e) {
        NodeList nlList = e.getElementsByTagName(tag).item(0).getChildNodes();
        Node nValue = (Node) nlList.item(0);
        return nValue.getNodeValue();
    }

But now, I want considering its attribute, so I must define what tag and the attribute to get the correct value. Thanks for the answer

Use an xpath query for this purpose. First create a query similar to this (eg to obtain field nodes with a certain value):

myQuery = xpath.compile("//field[@value=\"1234\"]");

Then populate a nodeset by running the query on the dom doc:

Object nodeSet = myQuery.evaluate(doc, XPathConstants.NODESET);

Change getTagValue as

private static String getTagValue(NodeList list, String name) {
    for (int i = 0; i < list.getLength(); i++) {
        Element e = (Element) list.item(i);
        if (e.getAttribute("name").equals(name)) {
            return e.getTextContent();
        }
    }
    return null;
}

public static void main(String[] args) throws Exception {
    Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder()
            .parse(new File("1.xml"));
    NodeList fields = doc.getElementsByTagName("field");
    String country = getTagValue(fields, "Country or Area");
    String year = getTagValue(fields, "Year");
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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