Just to summarize and learn.
XML files are often used in our development projects, and the following is a small example of Dom parsing.
The Domtestfile.xml file is as follows:
<?xml version= "1.0" encoding= "Utf-8"? ><menucontainer><menu order= "1.0" menuname= "Test 1" description= " Description 1 "><menu order=" 1.1 "><value> test 1</value></menu></menu><menu order=" 2.0 " Menuname= "Test 2" description= "description 2" ><menu order= "2.1" ><value> test 2</value></menu></menu ><menu order= "3.0" menuname= "Test 3" description= "description 3" ><menu order= "3.1" ><value> test 3</value ></menu></menu></MenuContainer>
The test classes are as follows:
1 PackageTest.dom;2 3 Importjava.io.IOException;4 ImportJava.io.InputStream;5 6 ImportJavax.xml.parsers.DocumentBuilder;7 Importjavax.xml.parsers.DocumentBuilderFactory;8 Importjavax.xml.parsers.ParserConfigurationException;9 Ten Importorg.w3c.dom.Document; One Importorg.w3c.dom.Element; A Importorg.w3c.dom.NodeList; - Importorg.xml.sax.SAXException; - the Public classDomtest { - - /** - * Dom Small example: XML-built menu file, parsing + * @paramargs - * @throwsparserconfigurationexception + * @throwsIOException A * @throwssaxexception at */ - Public Static voidMain (string[] args)throwsparserconfigurationexception, Saxexception, IOException { - -Documentbuilderfactory DBF =documentbuilderfactory.newinstance (); -Documentbuilder DOCB =Dbf.newdocumentbuilder (); - InputStream is in= Thread.CurrentThread (). Getcontextclassloader (). getResourceAsStream ("Domtestfile.xml"); - //Document Object toDocument doc =Docb.parse (IS); + //Get root node -Element Menucontainer =doc.getdocumentelement (); the //Get child nodes *NodeList NL =menucontainer.getchildnodes (); $ for(inti=0; I<nl.getlength (); i++) {Panax Notoginseng //Filter Text node - if(Nl.item (i). Getnodetype () = =Element.element_node) { theElement e =(Element) Nl.item (i); + //just the show ASystem.out.println ("Menu Order:" + E.getattribute ("order") + the", Menu Name:" + e.getattribute ("Menuname")); + } - $ } $ } - -}
The demo works as follows:
Java DOM Small Example