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 to get values ​​from this XML file using Java. In my file, I repeat child nodes.

0
source share
6 answers

There are many XML parsers, just google for it.

Example

+1
source

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

+3
source
+2

Java 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);
    }
  }
}
+2
+1

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

0
source

All Articles