WEB开发网
开发学院WEB开发Jsp 用java向XML增加一个结点元素(ACCP认证的机试题)... 阅读

用java向XML增加一个结点元素(ACCP认证的机试题)

 2008-01-05 08:35:19 来源:WEB开发网   
核心提示:用java向xml增加一个结点元素是今年ACCP认证考试的试题,可见XML的重要性!题目要求考生向已经给出的XML文件增加一个结点元素,用java向XML增加一个结点元素(ACCP认证的机试题),答案如下://DomXML.javaimport javax.xml.parsers.*; import javax.xml

  用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>

Tags:java XML 增加

编辑录入:爽爽 [复制链接] [打 印]
赞助商链接