XML编程总结(二)——使用DOM接口操作xml

(二)使用DOM接口操作xml

DOM解析器将整个XML文档加载到内存中,使用DOM模型对XML文档在内存中建模。DOM解析器被称为DocumentBuilder,它位于javax.xml.parsers包下。下面是使用DOM对xml文档进行CRUD操作的演示。

测试类代码:Source和Result接口的使用,将内存中xml模型输出

  1 public class DomTest {
  2     private Document document;
  3     
  4     @Before
  5     public void setUp() throws Exception{
  6         // 创建工厂对象
  7         DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
  8         // 创建构建器对象
  9         DocumentBuilder builder = factory.newDocumentBuilder();
 10         // 获取books.xml文档的输入流对象
 11         InputStream is = DomTest.class.getClassLoader().getResourceAsStream("books.xml");
 12         // 解析xml,在内存中构建DOM文档模型
 13         document = builder.parse(is);
 14     }
 15 
 16     
 17     /**
 18      * 查找book的属性为web的title和price节点的文本值
 19      */
 20     @Test
 21     public void testRetrieve() throws Exception{
 22         //获取book节点列表
 23         NodeList nodeList = document.getElementsByTagName("book");
 24         //遍历列表,找到属性为web的book节点
 25         for(int i=0;i<nodeList.getLength();i++){
 26             //将其转换为元素,带有属性,Node类型没有属性
 27             Element element = (Element) nodeList.item(i);
 28             String value = element.getAttribute("category");
 29             //判断属性值为WEB
 30             if("WEB".equals(value)){
 31                 //获取title子节点和price子节点
 32                 Node titleNode=element.getElementsByTagName("title").item(0);
 33                 Node priceNode = element.getElementsByTagName("price").item(0);
 34                 String titleText=titleNode.getTextContent();
 35                 String priceText = priceNode.getTextContent();
 36                 System.out.println("<title>"+titleText+"</title>"+
 37                             "<price>"+priceText+"</price>");
 38             }
 39         }
 40     }
 41     
 42     /**
 43      * 在第一个book元素前增加一个book元素
 44      * <book category="WEB">
 45           <title lang="en">Learning XML</title>
 46           <author>Erik T. Ray</author>
 47           <year>2003</year>
 48           <price>39.95</price>
 49         </book>
 50      * @throws Exception
 51      */
 52     @Test
 53     public void testCreate() throws Exception{
 54         //创建book节点,并创建属性
 55         Element bookElement = document.createElement("book");
 56         Attr attr = document.createAttribute("category");
 57         attr.setTextContent("JAVA");
 58         bookElement.setAttributeNode(attr);
 59         //创建title子节点
 60         Element titleElement=document.createElement("title");
 61         titleElement.setTextContent("Learning JDK8");
 62         //创建author节点
 63         Element authorElement = document.createElement("author");
 64         authorElement.setTextContent("zhang san");
 65         //创建year节点
 66         Element yearElement = document.createElement("year");
 67         yearElement.setTextContent("2013");
 68         //创建price节点
 69         Element priceElement = document.createElement("price");
 70         priceElement.setTextContent("119");
 71         //将这些节点添加到子节点book
 72         bookElement.appendChild(titleElement);
 73         bookElement.appendChild(authorElement);
 74         bookElement.appendChild(yearElement);
 75         bookElement.appendChild(priceElement);
 76         //获得根节点的位置
 77         Node node = document.getElementsByTagName("bookstore").item(0);
 78         //获得要插入引用的节点位置
 79         Node refChild = document.getElementsByTagName("book").item(3);
 80         //refChild=null,表示在最后位置插入
 81         node.insertBefore(bookElement, refChild);
 82         
 83         //打印到控制台
 84         this.transformTo(document);
 85     }
 86     
 87     /**
 88      * 更新下面book节点的price值
 89      * <book category="CHILDREN">
 90           <title lang="en">Harry Potter</title>
 91           <author>J K. Rowling</author>
 92           <year>2005</year>
 93           <price>29.99</price>
 94         </book>
 95      * @throws Exception
 96      */
 97     @Test
 98     public void testUpdate() throws Exception{
 99         //获得该book节点
100         Element element=(Element) document.getElementsByTagName("book").item(1);
101         //获得该price节点
102         Node priceNode = element.getElementsByTagName("price").item(0);
103         priceNode.setTextContent("49.99");
104         //获得year节点
105         Node yearNode=element.getElementsByTagName("year").item(0);
106         yearNode.setTextContent("2010");
107         
108         //打印到控制台
109         this.transformTo(document);
110     }
111     
112     /**
113      * 删除category值为WEB的book节点
114      * @throws Exception
115      */
116     @Test
117     public void testDelete() throws Exception{
118         //获得父节点
119         Element parent = (Element) document.getElementsByTagName("bookstore").item(0);
120         
121         //获得满足条件的子节点
122         NodeList nodeList = document.getElementsByTagName("book");
123         //存储要删除的节点,如果删除一个节点,内存中的DOM会立即变化
124         List<Node> list=new ArrayList<Node>();
125         for(int i=0;i<nodeList.getLength();i++){
126             Element item = (Element) nodeList.item(i);
127             String attr = item.getAttribute("category");
128             if("WEB".equals(attr)){
129                 //保存该节点
130                 list.add(item);
131             }
132         }
133         //遍历列表
134         if(list.size()>0){
135             for(int i=0;i<list.size();i++){
136                 //删除列表中的节点
137                 parent.removeChild(list.get(i));
138             }
139         }
140         
141         //打印到控制台
142         this.transformTo(document);
143     }
144     
145     /**
146      * 將DOM模型输出到控制台
147      * @param node
148      * @throws Exception
149      */
150     private void  transformTo(Node node) throws Exception{
151         // 构造转换器
152         TransformerFactory tf = TransformerFactory.newInstance();
153         Transformer transformer = tf.newTransformer();
154         // 指定源
155         Source xmlSource = new DOMSource(node);
156         // 指定目标
157         // OutputStream os=new FileOutputStream("books_new.xml");
158         Result outputTarget = new StreamResult(System.out);
159         transformer.transform(xmlSource, outputTarget);
160     }
161 }
posted @ 2016-10-15 19:13  悟道&匠心  阅读(1099)  评论(0编辑  收藏  举报