在已有的XML里,用JAVA代码,怎么追加进去

helphhhh 2004-11-22 01:44:44
<?xml version='1.0'?>
<!-- This file represents a fragment of a book store inventory database -->
<bookstore>
<book genre="novel" publicationdate="1967" ISBN="0-201-63361-2">
<title>The Confidence Man</title>
<author>
<first-name>Herman</first-name>
<last-name>Melville</last-name>
</author>
<price>11.99</price>
</book>
</bookstore>

比如像这样一个XML,我现在要再加入
<book genre="autobiography" publicationdate="1981" ISBN="1-861003-11-0">
<title>The Autobiography of Benjamin Franklin</title>
<author>
<first-name>Benjamin</first-name>
<last-name>Franklin</last-name>
</author>
<price>8.99</price>
</book>



最好写个例子,谢了
...全文
113 1 打赏 收藏 转发到动态 举报
写回复
用AI写文章
1 条回复
切换为时间正序
请发表友善的回复…
发表回复
zllzmcDCR 2004-11-22
  • 打赏
  • 举报
回复
下面这段代码里面告诉了你操作一棵DOM tree所需要的很多基本方法,
希望能对你有用,你还可以看下java文档下org.w3c.dom的相关部分。
private void writeXMLFile(String outFile) throws Exception {
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder df = null;
try{
df = dbf.newDocumentBuilder();
} catch (ParserConfigurationException pce) {
System.err.println(pce);
System.exit(1);
}
Document doc = null;
doc = df.newDocument();

Element root = doc.createElement("StudentRecord");
doc.appendChild(root);
for (int i = 0; i < studentVector.size(); i++) {
StudentBean studentBean = (StudentBean)studentVector.get(i);
Element student = doc.createElement("student");
student.setAttribute("sex" , studentBean.getSex());
root.appendChild(student);
Element age = doc.createElement("age");
student.appendChild(age);
Text tAge = doc.createTextNode(String.valueOf(studentBean.getAge()));
age.appendChild(tAge);
Element telnumber = doc.createElement("telnumber");
student.appendChild(telnumber);
Text tTlenumber = doc.createTextNode(studentBean.getPhone());
telnumber.appendChild(tTlenumber);

FileOutputStream outStream = new FileOutputStream(outFile);
OutputStreamWriter outWriter = new OutputStreamWriter(outStream);
((XmlDocument)doc).write(outWriter,"GB2312");
outWriter.close();
outStream.close();
}
}

8,906

社区成员

发帖
与我相关
我的任务
社区描述
XML/XSL相关问题讨论专区
社区管理员
  • XML/XSL社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧