利用Node修改數據

從flowers.xml文件中價格大於15的鮮花刪除,將其餘鮮花的價格減去5java

用到的Node的API包括:dom

1)Node removeChild(Node oldChild):從子節點列表中移除oldChild所指示的節點,並將其返回ui

2)void setTextContent(String textContent):設置此節點的文本內容spa

flowers.xml文件:code

 

<?xml version="1.0" encoding="UTF-8"?>
<flowers>
  <flower id="1">
     <name>玫瑰</name>
     <price>10</price>
  </flower>
  <flower id="2">
     <name>百合</name>
     <price>20</price>
  </flower>
   <flower id="3">
     <name>蘭花</name>
     <price>30</price>
  </flower>
</flowers>

WriteNode.java文件orm

 

import java.io.File;
import java.util.ArrayList;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
public class WriteNode {

	/**
	 * @param args
	 */
	public static void main(String[] args) throws Exception{
		// TODO Auto-generated method stub
		DocumentBuilderFactory dbf=DocumentBuilderFactory.newInstance();
		DocumentBuilder db=dbf.newDocumentBuilder();
		Document doc=db.parse("flowers.xml");
		//查詢全部價格
		NodeList list=doc.getElementsByTagName("price");
		ArrayList arrayList=new ArrayList();
		Node flowers=null;
		for(int i=0;i<list.getLength();i++){
			Node priceNode=list.item(i);
			String strPrice=priceNode.getTextContent();
			double price=Double.parseDouble(strPrice);
			//得到該價格的父節點
			Node flower=priceNode.getParentNode();
			//得到flower的父節點
			flowers=flower.getParentNode();
			if(price>15){
				arrayList.add(flower);
			}else{
				//修改價格
				String newPrice=String.valueOf(price-5);
				priceNode.setTextContent(newPrice);
			}
		}
		for(int j=0;j<arrayList.size();j++){
			Node flower=(Node)arrayList.get(j);
			//從flowers中刪除flower
			flowers.removeChild(flower);
		}
		//保存文件
				TransformerFactory tf=TransformerFactory.newInstance();
				Transformer transformer=tf.newTransformer();
				DOMSource source=new DOMSource(doc);  //將Document對象封裝爲DOM源
				File file=new File("newFlowers.xml");
				StreamResult result=new StreamResult(file); //經過StreamResult包裝File對象,肯定輸出的目標
				transformer.transform(source, result);  //利用Transformer的transform方法將源輸出到目標
				//System.out.println("保存成功!!");
	}

}

運行效果newFlowers.xml文件xml

相關文章
相關標籤/搜索