利用Element修改數據

Element的APIjava

1)void removeAttribute(String name):經過名稱移除屬性app

2)void setAttribute(String name,String value):給定屬性名稱和值,添加新屬性dom

下面將鮮花的id屬性改成編號屬性,而後在xml文件的最後添加節點:ui

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>

 WriteElement.javaorm

 

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.Element;
import org.w3c.dom.NodeList;
public class WriteElement {

	/**
	 * @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");
		//查詢全部flower
		NodeList  list=doc.getElementsByTagName("flower");
		for(int i=0;i<list.getLength();i++){
			Element flowerElement=(Element)list.item(i);
			//得到id屬性
			String id=flowerElement.getAttribute("id");
			//刪除id屬性
			flowerElement.removeAttribute("id");
			//添加"編號"屬性,值爲原先的id屬性值
			flowerElement.setAttribute("編號", id);
		}
		
		//建立一個新元素
		Element newFlower=doc.createElement("flower");
		newFlower.setAttribute("編號","4");
		Element newName=doc.createElement("name");
		newName.setTextContent("康乃馨");
		newFlower.appendChild(newName);
		Element newPrice=doc.createElement("price");
		newPrice.setTextContent("23");
		newFlower.appendChild(newPrice);
		//獲得根節點
		Element root=doc.getDocumentElement();
		//在根節點中添加newFlower
		root.appendChild(newFlower);
		
		//保存入文件
		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方法將源輸出到目標
	}

}

 顯示效果newFlower.xml文件xml

相關文章
相關標籤/搜索