0
<company>
   <company-name>xyz</company-name>
   <city>HYD</city>
   <company-name>ABC</company-name>
   <city>MUMBAI</city>
</company>

How can I get values from this xml file using Java. In my file I have repeated child nodes.

1
  • 3
    Did you try to use common parsers like dom4j or SAX? Commented May 10, 2011 at 8:42

6 Answers 6

3

I like JAXB a lot. Just define a XML-Schema file for your XML file and then use the Java tool xjc. You get beans and you easily bind the XML file to a graph of objects. Google is your friend :)

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

1 Comment

You can also start with Java classes and map them to XML via annotations (no schema required). Also since JAXB is a standard (JSR-222), there are multiple JAXB implementations to choose from: Metro (the reference implementation, EclipseLink MOXy, Apache JaxMe.
2

Maybe you could try XPath

Comments

2

Here's a simple solution based on Java's SAX API

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

public class Main {
  public static void main(String[] args) throws Exception {
    SAXParserFactory factory = SAXParserFactory.newInstance();
      SAXParser saxParser = factory.newSAXParser();
      MyHandler myHandler = new MyHandler();
      saxParser.parse(new File("g:/temp/x.xml"), myHandler);

      for(Pair p : myHandler.result) {
        System.out.println(p.a + ":" + p.b);
      }
  }

  public static final class Pair {
    public final String a;
    public final String b;

    public Pair(String a, String b) {
      this.a = a;
      this.b = b;
    }
  }

  public static class MyHandler extends DefaultHandler {    
    public final List<Pair> result = new ArrayList<Pair>();
    private StringBuilder sb = new StringBuilder();

    @Override
    public void endElement(String uri, String localName, String qName)
        throws SAXException {
      String s = sb.toString().trim();
      if(s.length() > 0)
        result.add(new Pair(qName, s));
      sb = new StringBuilder();
    }

    @Override
    public void characters(char[] ch, int start, int length)
        throws SAXException {
      sb.append(ch, start, length);
    }
  }
}

Comments

1

There are many XML parsers out there, simply google for it.

Example

Comments

1

Jdom is also a very good candidate for this work

Comments

0

If your format is really simple you can use readLine()/split/Scanner. However one of the many standard XML parsers is a safer choice.

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.