开发者

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>

H开发者_如何转开发ow can I get values from this xml file using Java. In my file I have repeated child nodes.


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


Maybe you could try XPath


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


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

Example


Jdom is also a very good candidate for this work


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜