user156073
user156073

Reputation: 2001

how to parse xml document in java using SAX approach

i want to parse a file which is similar to a HTML file . Its not exactly a html file.It can contain some user defined tags. I dont know in advance how the tags are nested in one another in advance.The tags may also have attributes. I think i shold use a SAX parser. Does java have a inbuilt SAX . Can i call a function when i encounter each tag?

Upvotes: 1

Views: 1663

Answers (3)

stevedbrown
stevedbrown

Reputation: 8934

SAX was originally Java only, so yes, Java has a built-in SAX parser. This will only work if your document is well formed.

Upvotes: 0

KV Prajapati
KV Prajapati

Reputation: 94625

Use following packages, java.io,javax.xml.parsers,org.xml.sax.

SAXParserFactory spf = SAXParserFactory.newInstance();
XMLReader reader = null;

  SAXParser parser = spf.newSAXParser();
  reader = parser.getXMLReader();

reader.setContentHandler(new MyContentHandler());

//XMLReader to parse the entire file.

  InputSource is = new InputSource(filename);
  reader.parse(is);

// Implements the methods of ContentHandler

class MyContentHandler implements ContentHandler {
}

Upvotes: 4

gustafc
gustafc

Reputation: 28865

I think you should use StAX instead, which is faster and easier to use than SAX. It's part of Java SE 6.

Upvotes: 2

Related Questions