This article briefly introduces the dom method for parsing xml by using sax. Because the method of parsing XML files by using a stream mechanism, it reads a row of xml files to parse a row, the code is written in the directory. For more information, see.
The Code is as follows: |
Copy code |
<? Xml version = "1.0" encoding = "UTF-8"?> <Students> <Student id = "1"> <Name> Yang Zhenyu </name> <Sno> 2008011123 </sno> <Sex> male </sex> <Phone> 18618405551 </phone> </Student> <Student id = "2"> <Name> Zhang Rui </name> <Sno> 2008011122 </sno> <Sex> male </sex> <Phone> 15120058124 </phone> </Student> <Student id = "3"> <Name> Chen Ming </name> <Sno> 2008011121 </sno> <Sex> male </sex> <Phone> 15801281851 </phone> </Student> <Student id = "4"> <Name> su Yujie </name> <Sno> 2008011120 </sno> <Sex> male </sex> <Phone> 18618405551 </phone> </Student> <Student id = "5"> <Name> Gaoyang </name> <Sno> 2008011145 </sno> <Sex> female </sex> <Phone> 18618405590 </phone> </Student> </Students>
|
You can use the following method for parsing:
The Code is as follows: |
Copy code |
Public static void parse (File file) throws Exception { DocumentBuilderFactory factory = DocumentBuilderFactory. newInstance (); DocumentBuilder builder = factory. newDocumentBuilder (); Document doc = builder. parse (file ); Element root = doc. getDocumentElement (); NodeList childList = root. getChildNodes (); For (int I = 0; I <childList. getLength (); I ++ ){ Node child = childList. item (I ); If (child instanceof Element ){ Element element = (Element) child; NodeList childInfo = element. getChildNodes (); For (int j = 0; j <childInfo. getLength (); j ++ ){ Node node = childInfo. item (j ); If (node instanceof Element ){ Element e = (Element) node; Log. v ("tag", "" + e. getTagName ()); Text textNode = (Text) e. getFirstChild (); String text = textNode. getData (). trim (); If (e. getTagName (). equals ("name ")) Log. v ("tag", "" + text ); Else if (e. getTagName (). equals ("sno ")) Log. v ("tag", "" + text ); Else if (e. getTagName (). equals ("sex ")) Log. v ("tag", "" + text ); Else if (e. getTagName (). equals ("phone ")) Log. v ("tag", "" + text ); } } } } } |