比如a.xml文件格式如下<title>
<info name = "liudehua" id= "123" />
</title>
这个xml文件经常在添加新的信息的属性,但是其格式不变,比如添加<info name="limin" id="234" />等等这个的信息,如何把添加的插到原来的xml中,即
<title>
<info name = "liudehua" id= "123" />
<info name="limin" id="234" />
</title>
<info name = "liudehua" id= "123" />
</title>
这个xml文件经常在添加新的信息的属性,但是其格式不变,比如添加<info name="limin" id="234" />等等这个的信息,如何把添加的插到原来的xml中,即
<title>
<info name = "liudehua" id= "123" />
<info name="limin" id="234" />
</title>
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;import org.jdom.Document;
import org.jdom.Element;
import org.jdom.input.SAXBuilder;
import org.jdom.output.Format;
import org.jdom.output.XMLOutputter;public class XMLTest { private String encode = "UTF-8"; private Document doc; private Element root; private XMLTest() {
} public static XMLTest initXML(File file) {
XMLTest msg = new XMLTest();
try {
SAXBuilder sb = new SAXBuilder();
msg.doc = sb.build(new FileReader(file));
msg.root = msg.doc.getRootElement();
} catch (Exception e) {
msg = null;
}
return msg;
} public boolean addNode(Element xmle) {
if (xmle.getParent() != null)
xmle.detach();
root.addContent(xmle);
return true;
} public String toString() {
try {
XMLOutputter xmlOut = new XMLOutputter(Format.getPrettyFormat()
.setOmitDeclaration(true).setEncoding(encode));
ByteArrayOutputStream out = new ByteArrayOutputStream();
xmlOut.output(doc, out);
return new String(out.toByteArray(), encode);
} catch (IOException e) {
return null;
}
} public static void main(String[] args) {
BufferedWriter bw = null;
try {
File f = new File("F:\\test.xml");
XMLTest xt = XMLTest.initXML(f);
System.out.println(xt.toString());
Element param = new Element("info");
param.setAttribute("name", "limin");
param.setAttribute("id", "234");
xt.addNode(param);
System.out.println(xt.toString());
bw = new BufferedWriter(new FileWriter(f, false));
bw.write(xt.toString());
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
bw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
IWAV0055I Java Bean test.XMLTest started with the main method
<title>
<info name="liudehua" id="123" />
</title>
<title>
<info name="liudehua" id="123" />
<info name="limin" id="234" />
</title>
XMLWriter writer = null;
SAXReader saxReader = new SAXReader();
OutputFormat format = OutputFormat.createPrettyPrint();
format.setEncoding("UTF-8");// 设置XML文件的编码格式
File file = new File("a.xml");
//a.xml并添加內容
InputStreamReader reader = new InputStreamReader(file, "UTF-8");
Document document = saxReader.read(reader);
Element root = document.addElement("title");//根节点
//增加节点
Element element = root.addElement("info");
element.addAttribute("name", "saxReader");//增加属性
element.addAttribute("id", "234");//增加属性
//写入文件
writer = new XMLWriter(new FileWriter(file),format);
writer.write(document);
writer.close();