DOM
またはAPIを使用SAX
して、XMLドキュメントを作成および解析できます。
XMLドキュメントを作成するためのDOMサンプル:
DocumentBuilderFactory factory=null;
DocumentBuilder builder=null;
try {
//1
factory=DocumentBuilderFactory.newInstance();
builder=factory.newDocumentBuilder();
//2
Document document=builder.newDocument();
//3
document.setXmlVersion("1.0");
//4
Node root=document.createElement("Students");
Element student=document.createElement("Student");
student.setAttribute("class", "1");
Element roll=document.createElement("Roll");
Element name=document.createElement("Name");
roll.appendChild(document.createTextNode("10"));
name.appendChild(document.createTextNode("Mr.X"));
student.appendChild(roll);
student.appendChild(name);
root.appendChild(student);
document.appendChild(root);
//5
TransformerFactory transFactory=TransformerFactory.newInstance();
Transformer trans=transFactory.newTransformer();
trans.setOutputProperty(OutputKeys.INDENT, "yes");
trans.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "5");
trans.transform(new DOMSource(document),new StreamResult("file.xml"));
} catch (Exception e) {
System.out.println(e);
}
XMLドキュメントを読み取る/解析するには:
DocumentBuilderFactory factory=null;
DocumentBuilder builder=null;
Document doc=null;
try {
factory=DocumentBuilderFactory.newInstance();
builder=factory.newDocumentBuilder();
doc=builder.parse("file.xml");
Element root=doc.getDocumentElement(); //root
NodeList list=root.getChildNodes();
for(int i=0;i<list.getLength();i++){
Node node=list.item(i);
switch(node.getNodeType()){
case Node.TEXT_NODE:
System.out.println("Text Node"); break;
case Node.ELEMENT_NODE:
case Node.ATTRIBUTE_NODE:
System.out.println("Element Node");
NodeList student=node.getChildNodes();
if(node.hasAttributes()){
System.out.println(node.getAttributes()
.getNamedItem("class").getTextContent());
}
for(int j=0;j<student.getLength();j++){
Node nd=student.item(j);
if(nd.getNodeType()==Node.ELEMENT_NODE){
System.out.println(nd.getNodeName() + " "
+ nd.getTextContent());
}
}
break;
default:
System.out.println("Other node");
break;
}
}
} catch (Exception e) {
System.out.println(e);
}