1 <?XML version= "1.0" encoding= "UTF-8"?>2 <Web-appxmlns= "Http://www.example.org/web-app_2_5" 3 Xmlns:xsi= "Http://www.w3.org/2001/XMLSchema-instance"4 xsi:schemalocation= "Http://www.example.org/web-app_2_5 web-app_2_5.xsd"5 version= "2.5">6 7 <servlet>8 <Servlet-name>Hello</Servlet-name>9 <Servlet-class>Doclwe4</Servlet-class>Ten </servlet> One <servlet-mapping> A <Servlet-name>Hello</Servlet-name> - <Url-pattern>/hello</Url-pattern> - </servlet-mapping> the - </Web-app>
1 PackageXmldemo;2 3 ImportJava.io.FileInputStream;4 Importjava.io.FileNotFoundException;5 ImportJava.io.InputStream;6 Importjava.util.List;7 8 Importjavax.xml.stream.events.StartDocument;9 Ten Importorg.dom4j.Document; One Importorg.dom4j.DocumentException; A Importorg.dom4j.Element; - ImportOrg.dom4j.io.SAXReader; - the - Public classDom4jdemo { - - Public Static voidMain (string[] args) { + //TODO auto-generated Method Stub - Try { + Testsaxreader (); A}Catch(Exception e) { at //Todo:handle Exception - e.printstacktrace (); - } - - } - in - Public Static voidTestsaxreader ()throwsdocumentexception, FileNotFoundException { toSaxreader Saxreader =NewSaxreader (); +FileInputStream file =NewFileInputStream ("Src/xmldemo/schemademo.xml"); -Document doc =saxreader.read (file); theElement root = Doc.getrootelement ();//Get root element *System.out.println (Root.getname ());//gets the name of the root element $System.out.println (Root.attributevalue ("version"));//gets the root element on the Version propertyPanax NotoginsengList<element> childselement =root.elements (); - for(Element child:childselement) { the if("Servlet". Equals (Child.getname ())) { + //get all the tags that are the servlet tags AElement servlet_name = child.element ("Servlet-name");//get the servlet-name tag . theElement Servlet_class = child.element ("Servlet-class");//get the Servlet-class tag . + System.out.println (Servlet_name.getdata ()); - System.out.println (Servlet_class.getdata ()); $ } $ } - - } the}
Java reads XML documents using DOM4J Demo