使用Transformer更新XML

package com.hqh.stax;

import java.io.InputStream;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Result;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathFactory;

import org.junit.Test;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;

public class TestUpdateElementVal {
	/**
	 * 1.使用xpath查找xml的节点
	 * 2.更新XML的节点
	 * 3.使用Transformer将更新后的XML文档进行输出
	 * 
	 * 需求:将books.xml中title='XQuery Kick Start'的book的price更新为100.00
	 */
	@Test
	public void testUpdateElement() {
		InputStream is = null;
		try {
			//将xml以流的形式转换为文档对象
			is = Thread.currentThread().getContextClassLoader()
					.getResourceAsStream("books.xml");
			DocumentBuilder builder = DocumentBuilderFactory.newInstance()
					.newDocumentBuilder();
			Document doc = builder.parse(is);
			
			//通过xpath定位到目标元素
			XPath xpath = XPathFactory.newInstance().newXPath();
			NodeList nodeList = (NodeList)xpath.evaluate("//book[title='XQuery Kick Start']", doc, XPathConstants.NODESET);
			Element bookElement = (Element)nodeList.item(0);
			Element priceElement = (Element)bookElement.getElementsByTagName("price").item(0);
			//---修改元素,设置新值---
			priceElement.setTextContent("100.00");
			
			
			//将更新后的xml进行输出
			Transformer trans = TransformerFactory.newInstance().newTransformer();
			trans.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
			//第一行换行
			trans.setOutputProperty(OutputKeys.INDENT,"yes");
			//指定转换后的结果输出目的地
			Result result = new StreamResult(System.out);
			//转换并输出
			trans.transform(new DOMSource(doc), result);
			
		} catch (Exception e) {
			e.printStackTrace();
		} finally {

		}
	}
}

你可能感兴趣的:(transform)