SURYA KARUTURI
SURYA KARUTURI

Reputation: 119

How to parse this XML using Java?

<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.

Upvotes: 0

Views: 1410

Answers (6)

Itay Maman
Itay Maman

Reputation: 30723

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

Upvotes: 2

DaveH
DaveH

Reputation: 7335

Jdom is also a very good candidate for this work

Upvotes: 1

Peter Lawrey
Peter Lawrey

Reputation: 533492

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

Upvotes: 0

Christian Ullenboom
Christian Ullenboom

Reputation: 1458

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 :)

Upvotes: 3

Stijn Geukens
Stijn Geukens

Reputation: 15628

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

Example

Upvotes: 1

Hons
Hons

Reputation: 4046

Maybe you could try XPath

Upvotes: 2

Related Questions