使用java如何修改某个xml文件中的某项内容
发布网友
发布时间:2022-04-23 06:03
我来回答
共1个回答
热心网友
时间:2022-05-04 18:25
代码如下:
import org.jdom.*;
import org.jdom.output.*;
import org.jdom.input.*;
import java.io.*;
public class xml{
public void toXml() throws JDOMException,IOException{
SAXBuilder saxBuilder=new SAXBuilder(false);
saxBuilder.setExpandEntities(false);
File file = new File("c:\\test.xml");
Document doc =saxBuilder.build(new File("c:\\test.xml"));
Element elem=doc.getRootElement();
//System.out.println(elem.toString());
elem.getChild("Collectors").getChild("Collector").getAttribute("HostIP").setValue("192.168.0.1");
elem.getChild("Collectors").getChild("Collector").getAttribute("PortID").setValue("100000");
Element elem1 = (Element)elem.clone();
Document Doc=new Document(elem1);
XMLOutputter XMLOut = new XMLOutputter();
XMLOut.setEncoding("BIG5");
XMLOut.setNewlines(true);
file.delete();
XMLOut.output(Doc,new FileOutputStream("c:\\test"+".xml"));
}
public static void main(String args[]){
xml x = new xml();
try{
x.toXml();
}catch(Exception e){}
}
}