javaでDOM(1)
Last-modified: 2013-08-24 (土) 02:14:21 (3496d)
Top / javaでDOM(1)
package example.ex3; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.io.StringReader; import java.io.StringWriter; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerException; 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.XPathExpression; import javax.xml.xpath.XPathExpressionException; import javax.xml.xpath.XPathFactory; import org.w3c.dom.Document; import org.w3c.dom.NodeList; import org.xml.sax.InputSource; import org.xml.sax.SAXException; public class XMLSample1 { private static final String IN_FILENAME="TestFileName.xml"; private static final String OUT_FILENAME="OUT.xml"; /** * @param args */ public static void main(String[] args) { // TODO 自動生成されたメソッド・スタブ try { // DocumentBuilderFactory インスタンスを取得 DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setNamespaceAware(true); // never forget this! File inputFile = new File(IN_FILENAME); BufferedReader br = new BufferedReader(new FileReader(IN_FILENAME)); StringBuffer in = new StringBuffer(); String tmp; while ((tmp = br.readLine()) != null){ in.append(tmp); } InputSource is = new InputSource(new StringReader(in.toString())); // DocumentBuilder を取得 DocumentBuilder builder = factory.newDocumentBuilder(); // DocumentBuilder を用いて Document オブジェクトを取得 // Document doc = builder.parse(new File(IN_FILENAME)); Document doc = builder.parse(is); XPathFactory xPathFactory = XPathFactory.newInstance(); XPath xpath = xPathFactory.newXPath(); XPathExpression expr = xpath.compile("//book[author='Neal Stephenson']/title/text()"); // XPathExpression expr = xpath.compile("//book"); Object result = expr.evaluate(doc, XPathConstants.NODESET); NodeList nodeList = (NodeList) result; for (int i = 0; i < nodeList.getLength(); i++) { System.out.println(nodeList.item(i).getNodeValue()); // doc.removeChild(nodeList.item(i)); } // System.out.println(doc.); StringWriter sw = new StringWriter(); TransformerFactory tff=TransformerFactory.newInstance(); Transformer tf = tff.newTransformer(); tf.setOutputProperty("encoding", "UTF-8"); tf.transform( new DOMSource(doc), new StreamResult(sw) ); System.out.println(sw); } catch (SAXException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (ParserConfigurationException e) { e.printStackTrace(); } catch (XPathExpressionException e) { e.printStackTrace(); } catch (TransformerException e) { // TODO 自動生成された catch ブロック e.printStackTrace(); } } }