利用Element修改数据

Element的API

1)void removeAttribute(String name):通过名称移除属性

2)void setAttribute(String name,String value):给定属性名称和值,添加新属性

下面将鲜花的id属性改为编号属性,然后在xml文件的最后添加节点:

flowers.xml文件

 

<?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.java

 

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文件

利用Element修改数据

你可能感兴趣的:(利用Element修改数据)