标签:
1、DOM方式解析(读取)XML文件
待解析(读取)的XML文件,直接放在项目根目录下即可
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> 10 <ide>Xcode</ide> 11 </lan> 12 <lan id="3"> 13 <name>C#</name> 14 <ide>Visual Studio</ide> 15 </lan> 16 17 </Language>
相应的解析(读取)java代码:
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; 10 import org.w3c.dom.Node; 11 import org.w3c.dom.NodeList; 12 import org.xml.sax.SAXException; 13 14 public class TestReadXML { 15 16 public static void main(String[] args) { 17 //DOM 18 try { 19 DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); 20 DocumentBuilder builder = factory.newDocumentBuilder(); 21 Document document = builder.parse(new File("languages.xml")); 22 Element root = document.getDocumentElement();//获取根元素 23 System.out.println("cat="+root.getAttribute("cat")); 24 NodeList list = root.getElementsByTagName("lan");//获取子元素lan 25 for(int i=0;i<list.getLength();i++){ 26 Element lan = (Element) list.item(i); 27 System.out.println("--------"); 28 System.out.println("id="+lan.getAttribute("id")); 29 30 // Element name = (Element) lan.getElementsByTagName("name").item(0);//不使用这种方法 31 // System.out.println("name="+name.getTextContent()); 32 33 NodeList clist = lan.getChildNodes();//获取lan的所有子元素 34 for(int j=0;j<clist.getLength();j++){ 35 Node c = clist.item(j); 36 if(c instanceof Element) 37 System.out.println(c.getNodeName()+"="+c.getTextContent()); 38 } 39 } 40 41 } catch (ParserConfigurationException e) { 42 43 e.printStackTrace(); 44 } catch (SAXException e) { 45 46 e.printStackTrace(); 47 } catch (IOException e) { 48 49 e.printStackTrace(); 50 } 51 } 52 53 }
标签:
原文地址:http://www.cnblogs.com/UniqueColor/p/5721247.html