更新XML,使用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 */@Testpublic 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 {}}}