xml-java
- 基于XPath的解析:
@Test
public void test01() {
InputStream is = null;
try {
is = Testxpath.class.getClassLoader().getResourceAsStream("books.xml");
DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder();
Document doc = db.parse(is);
XPath xpath = XPathFactory.newInstance().newXPath();
NodeList nodeList = (NodeList)xpath.evaluate("//book[@category='WEB']", doc,XPathConstants.NODESET);
for(int i=0; i<nodeList.getLength(); i++){
Element e = (Element)nodeList.item(i);
System.out.println(e.getElementsByTagName("title").item(0).getTextContent());
}
} catch (ParserConfigurationException e) {
e.printStackTrace();
} catch (SAXException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (XPathExpressionException e) {
e.printStackTrace();
}finally{
if( is!= null)
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
- 输出xml
@Test
public void test02(){
try {
XMLStreamWriter xsw = XMLOutputFactory.newInstance().createXMLStreamWriter(System.out);
xsw.writeStartDocument("UTF-8","1.0");
xsw.writeEndDocument();
xsw.writeStartElement("person");
xsw.writeStartElement("id");
xsw.writeCharacters("1");
xsw.writeEndElement();
xsw.writeEndElement();
xsw.flush();
xsw.close();
} catch (XMLStreamException e) {
e.printStackTrace();
} catch (FactoryConfigurationError e) {
e.printStackTrace();
}
} - 修改xml
@Test
public void test03() {
InputStream is = null;
try {
is = Testxpath.class.getClassLoader().getResourceAsStream("books.xml");
DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder();
Document doc = db.parse(is);
Transformer tf = TransformerFactory.newInstance().newTransformer();
tf.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
tf.setOutputProperty(OutputKeys.INDENT, "yes");
XPath xpath = XPathFactory.newInstance().newXPath();
NodeList nodeList = (NodeList)xpath.evaluate("//book[title='Learning XML']", doc,XPathConstants.NODESET);
Element e = (Element)(((Element)nodeList.item(0)).getElementsByTagName("price").item(0));
e.setTextContent("333.9");
Result result = new StreamResult(System.out);
tf.transform(new DOMSource(doc), result);
} catch (ParserConfigurationException e) {
e.printStackTrace();
} catch (SAXException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (XPathExpressionException e) {
e.printStackTrace();
} catch (TransformerConfigurationException e) {
e.printStackTrace();
} catch (TransformerFactoryConfigurationError e) {
e.printStackTrace();
} catch (TransformerException e1) {
e1.printStackTrace();
}finally{
if( is!= null)
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}