This example uses SAXDOMIX to do mixed SAX-DOM parsing.
Download Java source code, compiled classes and full documentation.
The parsing starts in SAX mode, which means that SAX events are forwarded to the application for handling. Certain XML elements trigger the switch to DOM. Each such element will be the root of a DOM tree constructed by SAXDOMIX. All sub-elements, character data, processing instructions and comments that are contained directly or indirectly by a root element will be part of the DOM tree. After building a DOM tree, SAXDOMIX forwards it to the application for handling. Then, SAXDOMIX returns to SAX parsing automatically.
In the case of this example, the handling of the SAX events and DOM trees consists of printing them to the output console. The names of the elements that trigger the switch from SAX to DOM are given in the command line.
We have the following MixedParsing.xml file:
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE root [
<!ELEMENT root (elem1, elem2)>
<!ELEMENT elem1 (elem11, elem12, elem13)>
<!ELEMENT elem11 (#PCDATA)>
<!ELEMENT elem12 (#PCDATA)>
<!ELEMENT elem13 (elem131, elem132)>
<!ELEMENT elem131 EMPTY>
<!ELEMENT elem132 EMPTY>
<!ELEMENT elem2 (elem21, elem22, elem23)>
<!ELEMENT elem21 (#PCDATA)>
<!ELEMENT elem22 (#PCDATA)>
<!ELEMENT elem23 (#PCDATA)>
]>
<root>
<elem1>
<!-- comment1 -->
<elem11>text11</elem11>
<elem12><![CDATA[cdata12]]></elem12>
<elem13>
<elem131/>
<elem132/>
</elem13>
<?proc1 data?>
</elem1>
<elem2>
<!-- comment2 -->
<elem21>data21</elem21>
<elem22><![CDATA[cdata22]]></elem22>
<elem23>text23</elem23>
<?proc2 data?>
</elem2>
</root>
Execute the following command to get the XML content of the elem1, elem21 and elem22 elements as DOM trees. The rest of the XML content is handled as SAX events.
java com.devsphere.examples.xml.saxdomix.MixedParsing
MixedParsing.xml -validation elem1 elem21 elem22
You'll get the following output:
SAX setDocumentLocator
SAX startDocument
SAX startElement root
DOM Tree
Element elem1
Comment comment1
Element elem11
Text text11
Element elem12
CDATASection cdata12
Element elem13
Element elem131
Element elem132
ProcessingInstruction proc1
SAX startElement elem2
DOM Tree
Element elem21
Text data21
DOM Tree
Element elem22
CDATASection cdata22
SAX startElement elem23
SAX characters text23
SAX endElement elem23
SAX processingInstruction proc2
SAX endElement elem2
SAX endElement root
SAX endDocument
|