Java笔记——XML解析
1 import java.io.File; 2 import java.io.IOException; 3 import javax.xml.parsers.DocumentBuilder; 4 import javax.xml.parsers.DocumentBuilderFactory; 5 import javax.xml.parsers.ParserConfigurationException; 6 import org.w3c.dom.Document; 7 import org.w3c.dom.Element; 8 import org.w3c.dom.Node; 9 import org.w3c.dom.NodeList; 10 import org.xml.sax.SAXException; 11 12 public class XmlTest { 13 14 public static void main(String[] args) { 15 16 try { 17 18 DocumentBuilderFactory builderFactory = DocumentBuilderFactory 19 .newInstance(); 20 DocumentBuilder builder = builderFactory.newDocumentBuilder(); 21 Document document = builder.parse(new File("NewFile.xml")); 22 Element root = document.getDocumentElement(); 23 System.out.println(root.getAttribute("name")+":"); 24 NodeList list = root.getElementsByTagName("student"); 25 for (int i = 0; i < list.getLength(); i++) { 26 Element student = (Element) list.item(i); 27 System.out.println("-----------------------"); 28 System.out.println("id= " + student.getAttribute("id")); 29 NodeList clist = student.getChildNodes(); 30 for (int j = 0; j < clist.getLength(); j++) { 31 Node c = clist.item(j); 32 if (c instanceof Element) { 33 System.out.println(c.getNodeName() + "=" 34 + c.getTextContent()); 35 } 36 } 37 } 38 39 } catch (ParserConfigurationException e) { 40 e.printStackTrace(); 41 } catch (SAXException e) { 42 e.printStackTrace(); 43 } catch (IOException e) { 44 e.printStackTrace(); 45 } 46 47 } 48 }
被解析的XML:
1 <?xml version="1.0" encoding="UTF-8"?> 2 <root name="StudentInformation"> 3 <student id="1"> 4 <name>张三</name> 5 <address>北京</address> 6 </student> 7 <student id="2"> 8 <name>李四</name> 9 <address>上海</address> 10 </student> 11 <student id="3"> 12 <name>王五</name> 13 <address>广州</address> 14 </student> 15 </root>
显示结果:
StudentInformation:
-----------------------
id= 1
name=张三
address=北京
-----------------------
id= 2
name=李四
address=上海
-----------------------
id= 3
name=王五
address=广州
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。