1. Parsing (reading) XML files in DOM mode
The XML file to be parsed (read), placed directly under the project root directory
1<?xml version="1.0"encoding="UTF-8"?>2<language cat="it">3 4<lan id="1">5<name>Java</name>6<ide>Eclipse</ide>7</lan>8<lan id="2">9<name>Swift</name>Ten<ide>Xcode</ide> One</lan> A<lan id="3"> -<name>C#</name> -<ide>visual studio</ide> the</lan> - -</Language>
The corresponding parsing (reading) Java code:
1 import Java.io.File;2 import java.io.IOException;3 4 import Javax.xml.parsers.DocumentBuilder;5 import javax.xml.parsers.DocumentBuilderFactory;6 import javax.xml.parsers.ParserConfigurationException;7 8 import org.w3c.dom.Document;9 import org.w3c.dom.Element;Ten import Org.w3c.dom.Node; One import org.w3c.dom.NodeList; A import org.xml.sax.SAXException; - - Public classTestreadxml { the - Public Static voidMain (string[] args) { - //DOM - Try { +Documentbuilderfactory factory =documentbuilderfactory.newinstance (); -Documentbuilder Builder =Factory.newdocumentbuilder (); +Document document = Builder.parse (NewFile ("languages.xml")); AElement root = Document.getdocumentelement ();//Get root element atSystem. out. println ("cat="+root.getattribute ("Cat")); -NodeList list = Root.getelementsbytagname ("LAN");//get child element LAN - for(intI=0; I<list.getlength (); i++){ -Element LAN =(Element) List.item (i); -System. out. println ("--------"); -System. out. println ("id="+lan.getattribute ("ID")); in - //element name = (Element) lan.getelementsbytagname ("name"). Item (0);//do not use this method to //System.out.println ("Name=" +name.gettextcontent ()); + -NodeList clist = Lan.getchildnodes ();//get all child elements of a LAN the for(intj=0; J<clist.getlength (); j + +){ *Node C =Clist.item (j); $ if(c instanceof Element)Panax NotoginsengSystem. out. println (C.getnodename () +"="+c.gettextcontent ()); - } the } + A}Catch(parserconfigurationexception e) { the + e.printstacktrace (); -}Catch(saxexception e) { $ $ e.printstacktrace (); -}Catch(IOException e) { - the e.printstacktrace (); - }Wuyi } the -}
XML operations in Java