用Java向XML增加一个结点元素是今年ACCP认证考试的试题,可见XML的重要性!
题目要求考生向已经给出的XML文件增加一个结点元素,答案如下:
//DomXML.java
import javax.xml.parsers.*;
import javax.xml.transform.*;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.*;
class XmlWrite
{
public static void main(String[] args)
{
try{
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder=factory.newDocumentBuilder();
Document doc=builder.parse("links.xml");
doc.normalize();
String name2="Hanzhong´s Homepage";
String sex2="male";
String phone2="22324098";
//create an element named "link"
Element link=doc.createElement("link");
/*create an element of context named "name"
context is consided with an element by w3c */
Element linkName=doc.createElement("name");
Text textName=doc.createTextNode(name2);
linkName.appendChild(textName);
link.appendChild(linkName);
doc.getDocumentElement().appendChild(link);//return a root node of document
TransformerFactory tFactory =TransformerFactory.newInstance();
Transformer transformer = tFactory.newTransformer();
DOMSource source = new DOMSource(doc);
StreamResult result = new StreamResult(new java.io.File("links.xml"));
transformer.transform(source, result);
}
catch(Exception e){}
}
}
//已经给出的links.xml(代码部分修改)
<?xml version="1.0" encoding="UTF-8"?>
<links>
<link>
<name>Java!</name>
<sex>male</sex>
<phone>2232307</phone>
</link>
</links>