java Dom(xml序列化及CUP)

package anby.com;

import java.io.File;
import java.io.IOException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.TransformerFactoryConfigurationError;
import javax.xml.transform.Result;
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.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

public class XmlCUP {
	Book book=new Book();
	public static void main(String args[]) throws Exception {
		Document doc = getDocument();
		 //获取根元素
		Element root=doc.getDocumentElement();
		  //创建子节点
		Element childroot=doc.createElement("book");
		//将子元素增加到根元素中
		root.appendChild(childroot);
		NodeList nodeHead = doc.getChildNodes();
		for (int i = 0; i < nodeHead.getLength(); i++) {
			Node childNode = nodeHead.item(i);
			Element ele = (Element) childNode;
			if ("titile".equals(ele.getElementsByTagName("id"))) {
               ele.setTextContent("b003");//修改节点内容
               //删除子节点就代表着删除父节点
               Node parent =ele.getParentNode();
               parent.removeChild(ele);
            
               
               
			}
		}
		
		SaveXml(doc);
	}
        //将Document对象保存为xml文档
	private static void SaveXml(Document doc) throws Exception {
		Transformer tansform = TransformerFactory.newInstance()
				.newTransformer();
		tansform.transform(new DOMSource(doc), new StreamResult("Result.xml"));

	}

	// 从xml文件中获取Document对象的实例
	public static Document getDocument() throws Exception {
		DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
		DocumentBuilder docbuilder = factory.newDocumentBuilder();
		Document doc = docbuilder.parse("Book.xml");
		return doc;
	}

}

  

 

<?xml version="1.0" encoding="UTF-8"?>
<Books>
  <book id="boo1">
  <titile>呐喊</titile>
   <price>18</price>
  </book>
  <book id="boo2">
  <titile>彷徨</titile>
   <price>15</price>
  </book>
  </Books>

  

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值