【Java】【XML】DOM [3]

DOM サンプル [3]

 DOM を使ったサンプルプログラム(要素の削除)

サンプル

removeChildNode.java

import org.w3c.dom.*;
import javax.xml.parsers.*;
import javax.xml.transform.*;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

public class removeChildNode {
	public static void main(String args[]) {
		try {
			DocumentBuilderFactory factory =
				DocumentBuilderFactory.newInstance();
			DocumentBuilder builder =
				factory.newDocumentBuilder();
			Document doc =
				builder.parse(".\\src\\employee.xml" );
			
			TransformerFactory tFactory =
				TransformerFactory.newInstance();
			Transformer tFormer =
				tFactory.newTransformer();
			
			Element element =
				(Element)doc.getElementsByTagName("id" ).item(0);
			element.getParentNode().removeChild(element);
			doc.normalize();
			
			Source source = new DOMSource(doc);
			Result result = new StreamResult(System.out);
			tFormer.transform(source, result);
			System.out.println();
		} catch (Exception ex) {
			System.out.println(ex);
			System.out.println("Parser not support" );
		}
	}
}

employee.xml(入力ファイル)

<?xml version="1.0"?>
<employee-detail>
	<employee>
		<Name>test1</Name>
		<id name="employee">id1</id>
		<email id="1">____xxx____1@xxx.com</email>
	</employee>
	<employee>
		<Name name="teacher">test2</Name>
		<id>id2</id>
		<email id="2">____xxx____2@xxx.com</email>
	</employee>
</employee-detail>

出力

* (『<Name>...</Name>』と『<email>.../email>』の間にあった「<id>...</id>」が削除されている)
<?xml version="1.0" encoding="UTF-8" standalone="no"?><employee-detail>
	<employee>
		<Name>test1</Name>
		
		<email id="1">____xxx____1@xxx.com</email>
	</employee>
	<employee>
		<Name name="teacher">test2</Name>
		<id>id2</id>
		<email id="2">____xxx____2@xxx.com</email>
	</employee>
</employee-detail>