解析xml的问题
XML如下(Books.xml):
<?xml version="1.0" encoding="GB2312"?>
<Information>
<Topic>信息主题</Topic>
<Content>信息的内容</Content>
<Date>2004-12-2</Date>
<Source>北京晚报</Source>
</Information>
Java代码如下(a.java):
import javax.xml.parsers.*;
import org.w3c.dom.*;
public class a
{
public static void main(String args[])
{
try
{
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder=factory.newDocumentBuilder();
Document doc=builder.parse("Books.xml");
NodeList nl =doc.getElementsByTagName("Information");
Element node=(Element) nl.item(0);
node.getElementsByTagName("Topic").item(0).getFirstChild().setNodeValue("aaa");
node.getElementsByTagName("Content").item(0).getFirstChild().setNodeValue("bbb");
node.getElementsByTagName("Date").item(0).getFirstChild().setNodeValue("ccc");
node.getElementsByTagName("Source").item(0).getFirstChild().setNodeValue("ddd");
}
catch(Exception e)
{
System.out.println(e.getMessage());
}
}
}
我已把节点的value重新赋值为aaa、bbb、ccc、ddd,为什么打开Boods.xml还是原来的数据???
好象必须save一下,怎么写那句话,能否帮我写一下,谢谢了
问题点数:20、回复次数:3Top
1 楼mydeman(漫步者)回复于 2004-12-03 14:49:57 得分 8
FileOutputStream output = new FileOutputStream("AddressBook.xml");
XMLOutputter out = new XMLOutputter();
out.setEncoding("GB2312");
out.output(doc,output);Top
2 楼mydeman(漫步者)回复于 2004-12-03 14:50:50 得分 2
更正一下:AddressBook.xml——〉Books.xmlTop
3 楼tom2005(随海奔跑)回复于 2004-12-03 15:03:01 得分 10
import javax.xml.parsers.*;
import org.w3c.dom.*;
import org.apache.crimson.tree.*;
import java.io.*;
public class a
{
public static void main(String args[])
{
try
{
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder=factory.newDocumentBuilder();
Document doc=builder.parse("Books.xml");
NodeList nl =doc.getElementsByTagName("Information");
Element node=(Element) nl.item(0);
node.getElementsByTagName("Topic").item(0).getFirstChild().setNodeValue("aaa");
node.getElementsByTagName("Content").item(0).getFirstChild().setNodeValue("bbb");
node.getElementsByTagName("Date").item(0).getFirstChild().setNodeValue("ccc");
node.getElementsByTagName("Source").item(0).getFirstChild().setNodeValue("ddd");
((XmlDocument)doc).write(new FileWriter("Books.xml"));
}
catch(Exception e)
{
System.out.println(e.getMessage());
}
}
}
Top




