1

To access the values id1 & id2 im iterating over every value in the XML and if I find a tag named id1 or id2 I read its value into a variable. Is there a better method of reading the values id1 & id2 ?

<begin>
  <total>1</total>
  <values>
    <factor>
      <base>test</base>
      <id1>id1</id1>
      <id2>id2</id2>
      <val>val2</val>
      <newval>val1</newval>
    </factor>
  </values>
</begin>
1
  • if all you interested is querying certain elements, xpath is your friend Commented Mar 28, 2012 at 19:49

5 Answers 5

1

If you use XPath, you can extract values directly from the Document object. In your case, the XPath to get to id1 would be /begin/id1.

Sign up to request clarification or add additional context in comments.

Comments

1

You can use the Java API for XML Processing. It's a very robust way of dealing with XML in Java.

Comments

1

Use a SAX parser and store the text emitted after the "id1" start element as the id1 value and the text after the "id2" start element as the id2 value.

For example:

public static List<String> getIds(InputStream xmlStream) throws ParserConfigurationException, SAXException, IOException {
  final List<String> ids = new ArrayList<String>();
  SAXParserFactory factory = SAXParserFactory.newInstance();
  SAXParser saxParser = factory.newSAXParser();
  saxParser.parse(xmlStream, new DefaultHandler() {
    boolean getChars = false;
    public void startElement(String uri, String name, String qName, Attributes attrs) throws SAXException {
      if ("id1".equalsIgnoreCase(qName)) getChars = true;
      if ("id2".equalsIgnoreCase(qName)) getChars = true;
    }
    public void characters(char cs[], int start, int len) throws SAXException {
      if (getChars) {
        ids.add(new String(cs, start, len));
        getChars = false;
      }
    }
  });
  return ids;
}

Comments

1

You can use JDOM for doing this:

import org.jdom.Document;
import org.jdom.input.SAXBuilder;

public class Test {

    public static void main(String[] args) throws Exception{
        SAXBuilder builder = new SAXBuilder();
        Document doc = builder.build("test.xml");
        String id1 = doc.getRootElement().getChild("values").getChild("factor").getChild("id1").getValue();
        System.out.println(id1);
        String id2 = doc.getRootElement().getChild("values").getChild("factor").getChild("id2").getValue();
        System.out.println(id2);
    }

}

Comments

0

I would use any library that supports XPath. JDOM is currently my favorite, but there are plenty out there.

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.