Java 解析 XML

来源:互联网 发布:js分割反斜杠字符串 编辑:程序博客网 时间:2024/06/07 10:33
由W3C提供的接口,它将整个XML文档读入内存,构建一个DOM树来对各个节点(Node)进行操作。
示例代码:

后文代码中有使用到text.xml(该文档放在src路径下,既编译后在classes路径下),都是指该xml文档。

[java] view plaincopyprint?
  1. package test.xml; 
  2.  
  3. import java.io.File; 
  4. import java.io.FileNotFoundException; 
  5. import java.io.FileOutputStream; 
  6. import java.io.IOException; 
  7. import java.io.InputStream; 
  8.  
  9. import javax.xml.parsers.DocumentBuilder; 
  10. import javax.xml.parsers.DocumentBuilderFactory; 
  11. import javax.xml.parsers.ParserConfigurationException; 
  12. import javax.xml.transform.Transformer; 
  13. import javax.xml.transform.TransformerConfigurationException; 
  14. import javax.xml.transform.TransformerException; 
  15. import javax.xml.transform.TransformerFactory; 
  16. import javax.xml.transform.dom.DOMSource; 
  17. import javax.xml.transform.stream.StreamResult; 
  18.  
  19. import org.w3c.dom.Document; 
  20. import org.w3c.dom.Element; 
  21. import org.w3c.dom.Node; 
  22. import org.w3c.dom.NodeList; 
  23. import org.w3c.dom.Text; 
  24. import org.xml.sax.SAXException; 
  25.  
  26. /**
  27. * dom读写xml
  28. * @author whwang
  29. */ 
  30. public class TestDom { 
  31.      
  32.     public static void main(String[] args) { 
  33.         read(); 
  34.         //write();  
  35.     } 
  36.      
  37.     publicstaticvoid read() { 
  38.         DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); 
  39.         try
  40.             DocumentBuilder builder = dbf.newDocumentBuilder(); 
  41.             InputStream in = TestDom.class.getClassLoader().getResourceAsStream("test.xml"); 
  42.             Document doc = builder.parse(in); 
  43.             // root <university> 
  44.             Element root = doc.getDocumentElement(); 
  45.             if (root ==null)return
  46.             System.err.println(root.getAttribute("name")); 
  47.             // all college node 
  48.             NodeList collegeNodes = root.getChildNodes(); 
  49.             if (collegeNodes ==null)return
  50.             for(int i =0; i < collegeNodes.getLength(); i++) { 
  51.                 Node college = collegeNodes.item(i); 
  52.                 if (college !=null && college.getNodeType() == Node.ELEMENT_NODE) { 
  53.                     System.err.println("\t" + college.getAttributes().getNamedItem("name").getNodeValue()); 
  54.                     // all class node 
  55.                     NodeList classNodes = college.getChildNodes(); 
  56.                     if (classNodes ==null)continue
  57.                     for (int j = 0; j < classNodes.getLength(); j++) { 
  58.                         Node clazz = classNodes.item(j); 
  59.                         if (clazz != null && clazz.getNodeType() == Node.ELEMENT_NODE) { 
  60.                             System.err.println("\t\t" + clazz.getAttributes().getNamedItem("name").getNodeValue()); 
  61.                             // all student node  
  62.                             NodeList studentNodes = clazz.getChildNodes(); 
  63.                             if (studentNodes == null) continue
  64.                             for (int k = 0; k < studentNodes.getLength(); k++) { 
  65.                                 Node student = studentNodes.item(k); 
  66.                                 if (student != null && student.getNodeType() == Node.ELEMENT_NODE) { 
  67.                                     System.err.print("\t\t\t" + student.getAttributes().getNamedItem("name").getNodeValue()); 
  68.                                     System.err.print(" " + student.getAttributes().getNamedItem("sex").getNodeValue()); 
  69.                                     System.err.println(" " + student.getAttributes().getNamedItem("age").getNodeValue()); 
  70.                                 } 
  71.                             } 
  72.                         } 
  73.                     } 
  74.                 } 
  75.             } 
  76.         } catch (ParserConfigurationException e) { 
  77.             e.printStackTrace(); 
  78.         } catch (FileNotFoundException e) { 
  79.             e.printStackTrace(); 
  80.         } catch (SAXException e) { 
  81.             e.printStackTrace(); 
  82.         } catch (IOException e) { 
  83.             e.printStackTrace(); 
  84.         } 
  85.          
  86.     } 
  87.      
  88.     public static void write() { 
  89.         DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); 
  90.         try
  91.             DocumentBuilder builder = dbf.newDocumentBuilder(); 
  92.             InputStream in = TestDom.class.getClassLoader().getResourceAsStream("test.xml"); 
  93.             Document doc = builder.parse(in); 
  94.             // root <university> 
  95.             Element root = doc.getDocumentElement(); 
  96.             if (root ==null)return
  97.             // 修改属性 
  98.             root.setAttribute("name","tsu"); 
  99.             NodeList collegeNodes = root.getChildNodes(); 
  100.             if (collegeNodes !=null) { 
  101.                 for (int i = 0; i <collegeNodes.getLength() -1; i++) { 
  102.                     // 删除节点 
  103.                     Node college = collegeNodes.item(i); 
  104.                     if (college.getNodeType() == Node.ELEMENT_NODE) { 
  105.                         String collegeName = college.getAttributes().getNamedItem("name").getNodeValue(); 
  106.                         if ("c1".equals(collegeName) ||"c2".equals(collegeName)) { 
  107.                             root.removeChild(college); 
  108.                         } else if ("c3".equals(collegeName)) { 
  109.                             Element newChild = doc.createElement("class"); 
  110.                             newChild.setAttribute("name","c4"); 
  111.                             college.appendChild(newChild); 
  112.                         } 
  113.                     } 
  114.                 } 
  115.             } 
  116.             // 新增节点  
  117.             Element addCollege = doc.createElement("college"); 
  118.             addCollege.setAttribute("name","c5"); 
  119.             root.appendChild(addCollege); 
  120.             Text text = doc.createTextNode("text"); 
  121.             addCollege.appendChild(text); 
  122.              
  123.             // 将修改后的文档保存到文件 
  124.             TransformerFactory transFactory = TransformerFactory.newInstance(); 
  125.             Transformer transFormer = transFactory.newTransformer(); 
  126.             DOMSource domSource = new DOMSource(doc); 
  127.             File file = new File("src/dom-modify.xml"); 
  128.             if (file.exists()) { 
  129.                 file.delete(); 
  130.             } 
  131.             file.createNewFile(); 
  132.             FileOutputStream out = new FileOutputStream(file);          
  133.             StreamResult xmlResult =new StreamResult(out); 
  134.             transFormer.transform(domSource, xmlResult); 
  135.             System.out.println(file.getAbsolutePath()); 
  136.         } catch (ParserConfigurationException e) { 
  137.             e.printStackTrace(); 
  138.         } catch (SAXException e) { 
  139.             e.printStackTrace(); 
  140.         } catch (IOException e) { 
  141.             e.printStackTrace(); 
  142.         } catch (TransformerConfigurationException e) { 
  143.             e.printStackTrace(); 
  144.         } catch (TransformerException e) { 
  145.             e.printStackTrace(); 
  146.         } 
  147.     } 
  148. }  
  149.  该代码只要稍做修改,即可变得更加简洁,无需一直写if来判断是否有子节点。
原创粉丝点击