0

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

2 Answers 2

1

Use an xpath query for this purpose. First create a query similar to this (e.g. 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);
Sign up to request clarification or add additional context in comments.

1 Comment

+1 - And the javax.xml.xpath APIs are included in the JDK/JRE starting with Java SE 5.
0

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");
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.