XML 使用Stax 创建xml文档及通过Transformer修改文档内容

xml文件放在src目录下

book.xml:

 

<?xml version="1.0" encoding="UTF-8"?>

 


<bookstore>
 
<book category="COOKING">
  <title lang="en">Everyday Italian</title>
  <author>Giada De Laurentiis</author>
  <year>2005</year>
  <price>30.00</price>
</book>

 


<book category="CHILDREN">
  <title lang="en">Harry Potter</title>
  <author>J K. Rowling</author>
  <year>2005</year>
  <price>29.99</price>
</book>

 

 
<book category="WEB">
  <title lang="en">Learning XML</title>
  <author>Erik T. Ray</author>
  <year>2003</year>
  <price>39.95</price>
</book>

 

</bookstore>

 

 

 

创建文档

// 基于Stax的文档创间
 @Test
 public void createXml01() {
  try {
   XMLStreamWriter writer = XMLOutputFactory.newInstance()
     .createXMLStreamWriter(System.out);
   writer.writeStartDocument("UTF-8", "1.0");
   writer.writeEndDocument();
   String ns = "http://11:dd";
   writer.writeStartElement("nssss", "person", ns);
   writer.writeStartDocument(ns, "id");
   writer.writeCData("1");
   writer.writeEndElement();
   writer.writeEndElement();
   writer.flush();
   writer.close();

  } catch (XMLStreamException e) {
   e.printStackTrace();
  } catch (FactoryConfigurationError e) {
   e.printStackTrace();
  }
 }


修改文档:

// 通过Transformer修改
 @Test
 public void updateXml() {
  InputStream stream = null;
  stream = TestStax.class.getClassLoader()
    .getResourceAsStream("book.xml");
  // 创建文档处理对象
  DocumentBuilder builder = null;
  try {
   builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
   // 通过DocumentBuilder创建文档对象
   Document document = builder.parse(stream);
   // 创建XPath
   XPath xPath = XPathFactory.newInstance().newXPath();
   Transformer transform = TransformerFactory.newInstance().newTransformer();
   
   transform.setParameter(OutputKeys.ENCODING, "UTF-8");
   
   NodeList nodeList = (NodeList) xPath
   .evaluate("//book[title='Learning XML']", document,
     XPathConstants.NODESET);
   //获取price节点
   Element be = (Element)nodeList.item(0);

   //获取price  把它修改成3000.00
   Element e = (Element)(be.getElementsByTagName("price").item(0));
   e.setTextContent("3000.00");
   
   Result result = new StreamResult(System.out);
   //通过Transformer修改
   transform.transform(new DOMSource(document),result);
   
  } catch (Exception e) {
   e.printStackTrace();
  }

 }
}

 

结果显示:

 

<?xml version="1.0" encoding="UTF-8" standalone="no"?><bookstore>
 
<book category="COOKING">
  <title lang="en">Everyday Italian</title>
  <author>Giada De Laurentiis</author>
  <year>2005</year>
  <price>30.00</price>
</book>

 


<book category="CHILDREN">
  <title lang="en">Harry Potter</title>
  <author>J K. Rowling</author>
  <year>2005</year>
  <price>29.99</price>
</book>

 

 
<book category="WEB">
  <title lang="en">Learning XML</title>
  <author>Erik T. Ray</author>
  <year>2003</year>
  <price>

3000.00</price>
</book>

 

</bookstore>

你可能感兴趣的:(transform)