前回の「JavaでDOM」でXMLファイルを読み込んで,ツリーを作成しそのツリーを探索したり,ノード情報を表示したりした.今回はこのツリーに要素を付加したり削除したりする.
要素の追加と削除
要素の追加と削除
XML文書は前回と同じものを使用する.プログラムは前回のDomSampleを拡張し,DomSample2にする.
import java.io.*;
import javax.xml.parsers.*;
import org.w3c.dom.*;
import org.apache.crimson.tree.*;
class DomSample2 extends DomSample{
public DomSample2(String filename){
super(filename);
}
public void getNodeInfo(Node node){
if(node.getNodeName()!="#text"){
tabbing();
System.out.println(node.getNodeName());
}
if(node.getNodeValue()!=null){
tabbing();
System.out.println(node.getNodeValue());
}
}
public void appendElement(){
Node root=doc.getDocumentElement();
Node child;
/* ルート要素の子要素に対して処理する */
for(child=root.getFirstChild();child!=null;child=child.getNextSibling()){
/* 要素ノードなら要素を追加 */
if(child.getNodeType()==Node.ELEMENT_NODE){
/* 新しい要素の作成 */
Element color=doc.createElement("color");
/* 新しい要素に付加するノードの作成 */
Text txt=doc.createTextNode("Yellow");
/* 要素を付加 */
child.appendChild(color);
/* ノードを付加 */
color.appendChild(txt);
}
}
}
public void appendText(){
Node root=doc.getDocumentElement();
Node child;
/* ルート要素の子要素に対して処理する */
for(child=root.getFirstChild();child!=null;child=child.getNextSibling()){
/* 要素ノードならテキストを追加 */
if(child.getNodeType()==Node.ELEMENT_NODE){
String str;
/* childのtype属性の値がalcoholなら */
if(child.getAttributes().getNamedItem("type").getNodeValue().equals("alcohol")){
str="お酒";
}else{
str="ソフトドリンク";
}
/* テキストノードを作成して付加 */
Text txt=doc.createTextNode(str);
child.appendChild(txt);
}
}
}
public void removeElement(){
Element root=doc.getDocumentElement();
Node child;
/* ルート要素の子ノードに対して処理する */
for(child=root.getFirstChild();child!=null;child=child.getNextSibling()){
/* ルート要素の子ノードchildの子ノードのリストを取得 */
NodeList nodeList=child.getChildNodes();
/* child全ての子ノードに対して処理 */
for(int i=0;i<nodeList.getLength();i++){
Node grandChild=child.getChildNodes().item(i);
/* ノード名がcolorならそのノードを削除 */
if(grandChild.getNodeName()=="color"){
child.removeChild(grandChild);
}
}
}
}
public static void main(String args[]){
DomSample2 ds=new DomSample2("sample.xml");
ds.appendElement();
ds.appendText();
ds.removeElement();
ds.walkThrough();
}
}
上を実行すると以下が出力される.
drinks
drink
name
Apple
taste
Good
ソフトドリンク
drink
name
Beer
taste
Bitter
お酒
drink
name
Whiskey
お酒
今回はタグ名か要素値のみ出力した.teste要素が削除され,テキストノードであるソフトドリンク/お酒が追加されている.