轉帖|其它|編輯:郝浩|2010-12-17 14:45:38.000|閱讀 1358 次
概述:本文提供了一個JDOM用簡單的Java程序來修改XML文件的方法,希望這篇文章能對大家有所幫助。
# 界面/圖表報表/文檔/IDE等千款熱門軟控件火熱銷售中 >>
本文詳細介紹Java的文檔對象模型--JDOM (Java Document Object Model)提供了一個完整的用于訪問基于Java的解決方案,JDOM是用Java代碼控制、輸出XML 數據來完成這項工作的。在JDOM上明確規定了使用一個Java代碼如何修改XML文檔。我們首先需要下載JDOM的壓縮文件并添加到項目庫文件夾中,下面是對XML文件進行修改:
sample.xml
1.<root>
2.<firsttag tag="file">
3.<firstsubtag>first subtag</firstsubtag>
4.</firsttag>
5.<secondtag>second tag</secondtag>
6.</root>
7.
下面的Java代碼用于更新或修改一個XML 文件。
8.import java.io.File;
9.import java.io.FileWriter;
10.import org.jdom.Document;
11.import org.jdom.Element;
12.import org.jdom.input.SAXBuilder;
13.import org.jdom.output.XMLOutputter;
14./**
15.* @author giftsam
16.*/
17.public class XMLModifier
18.{
19./**
20.* This method is used to modify the data's of an XML file
21.*/
22.private void modifyXML()
23.{
24.try
25.{
26./**
27.* Initializing the SAXBuilder class
28.*/
29.SAXBuilder builder = new SAXBuilder();
30.String filePath = "E:" + File.separator + "xml" + File.separator +"sample.xml";
31.System.out.println("File path is: " + filePath);
32.File file = new File(filePath);
33.if (file.exists())
34.{
35.Document document = (Document) builder.build(file);
36./**
37.* Get the root element from the document class instance and from the root element get all the child elements and
38.* replace the appropriate values
39.*/
40.Element root = document.getRootElement();
41.Element firstElement = root.getChild("firsttag");
42.f irstElement.getAttribute("tag").setValue("file");
43.
44.firstElement.getChild("firstsubelement").setText("test");
45.Element secondElement = root.getChild("secondtag");
46.secondElement.setText("This is the second tag");
47.
48./**
49.* Print the modified xml document
50.*/
51.String xmlFileData= new XMLOutputter().outputString(document);
52.System.out.println("Modified XML file is : " + xmlFileData);
53.
54./**
55.* Modify the orginal document using FileWritter
56.*/
57.FileWriter fileWriter = new FileWriter(file);
58.fileWriter.write(des);
59.fileWriter.close();
60.}
61.else
62.{
63.System.out.println("File does not exist");
64.}
65.}
66.catch (Exception ex)
67.{
68.ex.printStackTrace();
69.}
70.}
71.
72.public static void main(String argS[])
73.{
74.try
75.{
76.new XMLModifier().modifyXML();
77.}
78.catch (Exception ex)
79.{
80.ex.printStackTrace();
81.}
82.}
83.}
下面的是修改后的XML文件。
sample.xml(Modified)
84.<root>
85.<firsttag tag="test">
86.<firstsubtag>This is the first sub tag</firstsubtag>
87.</firsttag>
88.<secondtag>This is the second tag</secondtag>
89.</root>
本文提供了一個JDOM用簡單的Java程序來修改XML文件的方法,希望這篇文章能對大家有所幫助。
本站文章除注明轉載外,均為本站原創或翻譯。歡迎任何形式的轉載,但請務必注明出處、不得修改原文相關鏈接,如果存在內容上的異議請郵件反饋至chenjj@fc6vip.cn
文章轉載自:網絡轉載