<p>I'm looking for the best method to parse various XML documents using a Java application.  I'm currently doing this with SAX and a custom content handler and it works great - zippy and stable. </p>

<p>I've decided to explore the option having the same program, that currently recieves a single format XML document, receive two additional XML document formats, with various XML element changes.  I was hoping to just swap out the ContentHandler with an appropriate one based on the first "startElement" in the document... but, uh-duh, the ContentHandler is set and <strong>then</strong> the document is parsed!</p>

<pre><code>... constructor ...
{
SAXParserFactory spf = SAXParserFactory.newInstance();

try {
SAXParser sp = spf.newSAXParser();
parser = sp.getXMLReader();
parser.setErrorHandler(new MyErrorHandler());
} catch (Exception e) {} 

... parse StringBuffer ...
try {
parser.setContentHandler(pP);
parser.parse(new InputSource(new StringReader(xml.toString())));
return true;
} catch (IOException e) {
    e.printStackTrace();
} catch (SAXException e) {
    e.printStackTrace();
}
...
</code></pre>

<p>So, it doesn't appear that I can do this in the way I initially thought I could.</p>

<p>That being said, am I looking at this entirely wrong?  What is the best method to parse multiple, discrete XML documents with the same XML handling code?  <a href="https://stackoverflow.com/questions/23106/best-method-to-parse-various-custom-xml-documents-in-java">I tried to ask in a more general post earlier... but, I think I was being too vague</a>.  For speed and efficiency purposes I never really looked at DOM because these XML documents are fairly large and the system receives about 1200 every few minutes.  It's just a one way send of information</p>

<p>To make this question too long and add to my confusion; following is a mockup of some various XML documents that I would like to have a single SAX, StAX, or ?? parser cleanly deal with. </p>

<p>products.xml:</p>

<pre><code>&lt;products&gt;
&lt;product&gt;
  &lt;id&gt;1&lt;/id&gt;
  &lt;name&gt;Foo&lt;/name&gt;
&lt;product&gt;
  &lt;id&gt;2&lt;/id&gt;
  &lt;name&gt;bar&lt;/name&gt;
&lt;/product&gt;
&lt;/products&gt;
</code></pre>

<p>stores.xml:</p>

<pre><code>&lt;stores&gt;
&lt;store&gt;
  &lt;id&gt;1&lt;/id&gt;
  &lt;name&gt;S1A&lt;/name&gt;
  &lt;location&gt;CA&lt;/location&gt;
&lt;/store&gt;
&lt;store&gt;
  &lt;id&gt;2&lt;/id&gt;
  &lt;name&gt;A1S&lt;/name&gt;
  &lt;location&gt;NY&lt;/location&gt;
&lt;/store&gt;
&lt;/stores&gt;
</code></pre>

<p>managers.xml:</p>

<pre><code>&lt;managers&gt;
&lt;manager&gt;
  &lt;id&gt;1&lt;/id&gt;
  &lt;name&gt;Fen&lt;/name&gt;
  &lt;store&gt;1&lt;/store&gt;
&lt;/manager&gt;
&lt;manager&gt;
  &lt;id&gt;2&lt;/id&gt;
  &lt;name&gt;Diz&lt;/name&gt;
  &lt;store&gt;2&lt;/store&gt;
&lt;/manager&gt;
&lt;/managers&gt;
</code></pre>

[{'answer_id': 30673, 'author': 'Vinnie', 'author_id': 2890, 'author_profile': 'https://Stackoverflow.com/users/2890', 'pm_score': 1, 'selected': False, 'text': '<p><a href="http://java.sun.com/developer/technicalArticles/WebServices/jaxb/" rel="nofollow noreferrer"><strong>JAXB</strong></a>. The Java Architecture for XML Binding.  Basically you create an xsd defining your XML layout (I believe you could also use a DTD).  Then you pass the XSD to the JAXB compiler and the compiler creates Java classes to marshal and unmarshal your XML document into Java objects.  It\'s really simple.</p>\n\n<p>BTW, there are command line options to jaxb to specify the package name you want to place the resulting classes in, etc.</p>\n'}, {'answer_id': 30677, 'author': 'Brian Matthews', 'author_id': 1969, 'author_profile': 'https://Stackoverflow.com/users/1969', 'pm_score': 2, 'selected': False, 'text': '<p>You\'ve done a good job of explaining what you want to do but not why. There are several XML frameworks that simplify marshalling and unmarshalling Java objects to/from XML. </p>\n\n<p>The simplest is <a href="http://commons.apache.org/digester/" rel="nofollow noreferrer">Commons Digester</a> which I typically use to parse configuration files. But if you are want to deal with Java objects then you should look at <a href="http://castor.org/" rel="nofollow noreferrer">Castor</a>, <a href="http://jibx.sourceforge.net/" rel="nofollow noreferrer">JiBX</a>, <a href="http://jaxb.java.net/" rel="nofollow noreferrer">JAXB</a>, <a href="http://xmlbeans.apache.org/" rel="nofollow noreferrer">XMLBeans</a>, <a href="http://xstream.codehaus.org/" rel="nofollow noreferrer">XStream</a>, or something similar. Castor or JiBX are my two favourites.</p>\n'}, {'answer_id': 30689, 'author': 'Bernie Perez', 'author_id': 1992, 'author_profile': 'https://Stackoverflow.com/users/1992', 'pm_score': 2, 'selected': False, 'text': '<p>I have tried the SAXParser once, but once I found <a href="http://xstream.codehaus.org/" rel="nofollow noreferrer">XStream</a> I never went back to it. With XStream you can create Java Objects and convert them to XML. Send them over and use XStream to recreate the object. Very easy to use, fast, and creates clean XML.</p>\n\n<p>Either way you have to know what data your going to receiver from the XML file. You can send them over in different ways to know which parser to use. Or have a data object that can hold everything but only one structure is populated (product/store/managers). Maybe something like:</p>\n\n<pre><code>public class DataStructure {\n\n    List&lt;ProductStructure&gt; products;\n\n    List&lt;StoreStructure&gt; stors;\n\n    List&lt;ManagerStructure&gt; managers;\n\n    ...\n\n    public int getProductCount() {\n        return products.lenght();\n    }\n\n    ...\n}\n</code></pre>\n\n<p>And with XStream convert to XML send over and then recreate the object. Then do what you want with it.</p>\n'}, {'answer_id': 30697, 'author': 'McDowell', 'author_id': 304, 'author_profile': 'https://Stackoverflow.com/users/304', 'pm_score': 3, 'selected': True, 'text': "<p>As I understand it, the problem is that you don't know what format the document is prior to parsing. You could use a delegate pattern. I'm assuming you're not validating against a DTD/XSD/etcetera and that it is OK for the DefaultHandler to have state.</p>\n\n<pre><code>public class DelegatingHandler extends DefaultHandler {\n\n    private Map&lt;String, DefaultHandler&gt; saxHandlers;\n    private DefaultHandler delegate = null;\n\n    public DelegatingHandler(Map&lt;String, DefaultHandler&gt; delegates) {\n        saxHandlers = delegates;\n    }\n\n    @Override\n    public void startElement(String uri, String localName, String name,\n            Attributes attributes) throws SAXException {\n       if(delegate == null) {\n           delegate = saxHandlers.get(name);\n       }\n       delegate.startElement(uri, localName, name, attributes);\n    }\n\n    @Override\n    public void endElement(String uri, String localName, String name)\n            throws SAXException {\n        delegate.endElement(uri, localName, name);\n    }\n\n//etcetera...\n</code></pre>\n"}, {'answer_id': 30896, 'author': 'jelovirt', 'author_id': 2679, 'author_profile': 'https://Stackoverflow.com/users/2679', 'pm_score': 2, 'selected': False, 'text': '<p>See the documentation for <a href="http://www.saxproject.org/apidoc/org/xml/sax/XMLReader.html#setContentHandler(org.xml.sax.ContentHandler)" rel="nofollow noreferrer">XMLReader.setContentHandler()</a>, it says:</p>\n\n<blockquote>\n  <p>Applications may register a new or different handler in the middle of a parse, and the SAX parser must begin using the new handler immediately.</p>\n</blockquote>\n\n<p>Thus, you should be able to create a <code>SelectorContentHandler</code> that consumes events until the first <code>startElement</code> event, based on that changes the <code>ContentHandler</code> on the XML reader, and passes the first start element event to the new content handler. You just have to pass the <code>XMLReader</code> to the <code>SelectorContentHandler</code> in the constructor. If you need <strong>all</strong> the events to be passes to the vocabulary specific content handler, <code>SelectorContentHandler</code> has to cache the events and then pass them, but in most cases this is not needed.</p>\n\n<p>On a side note, I\'ve lately used <a href="http://xom.nu/" rel="nofollow noreferrer">XOM</a> in almost all my projects to handle XML ja thus far performance hasn\'t been the issue.</p>\n'}, {'answer_id': 423223, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 0, 'selected': False, 'text': "<p>If you want more dynamic handling, Stax approach would probably work better than Sax.\nThat's quite low-level, still; if you want simpler approach, XStream and JAXB are my favorites. But they do require quite rigid objects to map to.</p>\n"}, {'answer_id': 424424, 'author': 'ghbuch', 'author_id': 4952, 'author_profile': 'https://Stackoverflow.com/users/4952', 'pm_score': 0, 'selected': False, 'text': "<p>Agree with StaxMan, who interestingly enough wants you to use Stax.  It's a pull based parser instead of the push you are currently using.  This would require some significant changes to your code though.</p>\n"}, {'answer_id': 485082, 'author': 'StaxMan', 'author_id': 59501, 'author_profile': 'https://Stackoverflow.com/users/59501', 'pm_score': 0, 'selected': False, 'text': '<p>:-)</p>\n\n<p>Yes, I have some bias towards Stax. But as I said, oftentimes data binding is more convenient than streaming solution. But if it\'s streaming you want, and don\'t need pipelining (of multiple filtering stages), Stax is simpler than SAX.</p>\n\n<p>One more thing: as good as XOM is (wrt alternatives), often Tree Model is not the right thing to use if  you are not dealing with "document-centric" xml  (~= xhtml pages, docbook, open office docs).\nFor data interchange, config files etc data binding is more convenient, more efficient, more natural. Just say no to tree models like DOM for these use cases.\nSo, JAXB, XStream, JibX are good. Or, for more acquired taste, digester, castor, xmlbeans.</p>\n'}, {'answer_id': 36521605, 'author': 'vtd-xml-author', 'author_id': 129732, 'author_profile': 'https://Stackoverflow.com/users/129732', 'pm_score': 0, 'selected': False, 'text': '<p>VTD-XML is known for being the best XML processing technology for heavy duty XML processing. See the reference below for a proof</p>\n\n<p><a href="http://sdiwc.us/digitlib/journal_paper.php?paper=00000582.pdf" rel="nofollow">http://sdiwc.us/digitlib/journal_paper.php?paper=00000582.pdf</a></p>\n'}]
['https://Stackoverflow.com/questions/30627', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/828/']