Java Reference
In-Depth Information
NodeList nl = e.getChildNodes();
for (int i = 0; i < nl.getLength(); i++)
{
Node node = nl.item(i);
if (node instanceof Element)
dump((Element) node);
}
}
}
DOMDemo isdesignedtorunatthecommandline.Afterverifyingthatonecommand-
lineargument(thenameofanXMLdocument)hasbeenspecified, main() creates a
document builder factory, informs the factory that it wants a namespace-aware docu-
ment builder, and has the factory return this document builder.
Continuing, main() parsesthedocumentintoanodetree;outputstheXMLdeclara-
tion'sversionnumber,encoding,andstandaloneattributevalues;andrecursivelydumps
all element nodes (starting with the root node) and their attribute values.
Note Regarding the multiple catch blocks, consider it an exercise to replace them
with multicatch.
Notice the use of getNodeType() in one part of this listing and instanceof
in another part. The getNodeType() method call isn't necessary (it is only present
fordemonstration)because instanceof canbeusedinstead.However,thecastfrom
Node type to Element type in the dump() method calls is necessary.
Assuming that you've compiled the source code, execute java DOMDemo art-
icle.xml to dump Listing 10-3 ' s article XML content. You should observe the fol-
lowing output:
Version = 1.0
Encoding = null
Standalone = false
Element: article, article, null, null
Attribute lang = en
Attribute title = The Rebirth of JavaFX
Element: abstract, abstract, null, null
Search WWH ::




Custom Search