« J2SE5.0でXPath | Main | Subversion and Javahl »

2005.07.21

J2SE5.0でXPath(2)

ついでに、DOMを用いた操作も試してみました。mainメソッド内のみを記述します。
Nodeの除去を行ってみるテストです。


try {
DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
documentBuilderFactory.setNamespaceAware(false);
DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();

Document document = documentBuilder.parse(new InputSource(new StringReader(sampleXML)));

String xpathvalue = "/学生マスタ/学生/番号";
XPath xpath = XPathFactory.newInstance().newXPath();

NodeList nodes = (NodeList) xpath.evaluate(
xpathvalue, document, XPathConstants.NODESET
);

int length = nodes.getLength();
for (int n = 0 ; n < length ; n++) {
Node node = nodes.item(n);
Node parent = node.getParentNode();
parent.removeChild(node);
}

TransformerFactory transFactory = TransformerFactory.newInstance();
Transformer transformer = transFactory.newTransformer();
DOMSource source = new DOMSource(document);
StringWriter sw = new StringWriter();
StreamResult result = new StreamResult(sw);
transformer.transform(source, result);
sw.close();
System.out.println(sw.toString());
} catch (Exception e) {
e.printStackTrace();
}


指定した値を持つNodeの除去を行ってみる(番号が1235である学生のデータを除去してみる)テストです。

try {
DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
documentBuilderFactory.setNamespaceAware(false);
DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();

Document document = documentBuilder.parse(new InputSource(new StringReader(sampleXML)));

String xpathvalue = "/学生マスタ/学生[番号=1235]";
XPath xpath = XPathFactory.newInstance().newXPath();

NodeList nodes = (NodeList) xpath.evaluate(
xpathvalue, document, XPathConstants.NODESET
);

int length = nodes.getLength();
for (int n = 0 ; n < length ; n++) {
Node node = nodes.item(n);
Node parent = node.getParentNode();
parent.removeChild(node);
}

TransformerFactory transFactory = TransformerFactory.newInstance();
Transformer transformer = transFactory.newTransformer();
DOMSource source = new DOMSource(document);
StringWriter sw = new StringWriter();
StreamResult result = new StreamResult(sw);
transformer.transform(source, result);
sw.close();
System.out.println(sw.toString());
} catch (Exception e) {
e.printStackTrace();
}

 後はXPathの記述の仕方そのものの勉強だな・・・。

#Transformerを用いると、改行がなくなってしまうのは仕方がないの??

|

« J2SE5.0でXPath | Main | Subversion and Javahl »

Java」カテゴリの記事

Comments

Post a comment



(Not displayed with comment.)


Comments are moderated, and will not appear on this weblog until the author has approved them.



TrackBack

TrackBack URL for this entry:
http://app.cocolog-nifty.com/t/trackback/3959/5074916

Listed below are links to weblogs that reference J2SE5.0でXPath(2):

« J2SE5.0でXPath | Main | Subversion and Javahl »