對xml節點進行修改和編寫

@Test
public void test07() throws XMLStreamException, FactoryConfigurationError{
XMLStreamWriter xw=XMLOutputFactory.newInstance().createXMLStreamWriter(System.out);
xw.writeStartDocument("UTF-8","1.0");
xw.writeEndDocument();
xw.writeStartElement("person");
xw.writeStartElement("id");
xw.writeCharacters("1");
xw.writeEndElement();
xw.writeEndElement();
xw.flush();
xw.close();
}

@Test
public void test08() throws ParserConfigurationException, XPathExpressionException, IOException, SAXException, TransformerFactoryConfigurationError, TransformerException{
InputStream is=TestStax.class.getClassLoader().getResourceAsStream("books.xml");
//創建文檔處理對象
DocumentBuilder db=DocumentBuilderFactory.newInstance().newDocumentBuilder();
Document doc=db.parse(is);
Transformer transformer=TransformerFactory.newInstance().newTransformer();
transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
//創建xpath對象
XPath xPath=XPathFactory.newInstance().newXPath();
//第一個參數表達式,第二個文檔,第三個參數是返回類型
NodeList list=(NodeList) xPath.evaluate("//book[title='Learning XML']", doc,XPathConstants.NODESET);
Element e=(Element) ((Element) list.item(0)).getElementsByTagName("price").item(0);
e.setTextContent("100.89");
transformer.transform(new DOMSource(doc), new StreamResult(System.out));
if(is!=null){
is.close();
}
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章