轉(zhuǎn)帖|其它|編輯:郝浩|2010-12-17 14:45:38.000|閱讀 1358 次
概述:本文提供了一個(gè)JDOM用簡(jiǎn)單的Java程序來(lái)修改XML文件的方法,希望這篇文章能對(duì)大家有所幫助。
# 界面/圖表報(bào)表/文檔/IDE等千款熱門(mén)軟控件火熱銷售中 >>
本文詳細(xì)介紹Java的文檔對(duì)象模型--JDOM (Java Document Object Model)提供了一個(gè)完整的用于訪問(wèn)基于Java的解決方案,JDOM是用Java代碼控制、輸出XML 數(shù)據(jù)來(lái)完成這項(xiàng)工作的。在JDOM上明確規(guī)定了使用一個(gè)Java代碼如何修改XML文檔。我們首先需要下載JDOM的壓縮文件并添加到項(xiàng)目庫(kù)文件夾中,下面是對(duì)XML文件進(jìn)行修改:
sample.xml
1.<root>
2.<firsttag tag="file">
3.<firstsubtag>first subtag</firstsubtag>
4.</firsttag>
5.<secondtag>second tag</secondtag>
6.</root>
7.
下面的Java代碼用于更新或修改一個(gè)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>
本文提供了一個(gè)JDOM用簡(jiǎn)單的Java程序來(lái)修改XML文件的方法,希望這篇文章能對(duì)大家有所幫助。
本站文章除注明轉(zhuǎn)載外,均為本站原創(chuàng)或翻譯。歡迎任何形式的轉(zhuǎn)載,但請(qǐng)務(wù)必注明出處、不得修改原文相關(guān)鏈接,如果存在內(nèi)容上的異議請(qǐng)郵件反饋至chenjj@fc6vip.cn
文章轉(zhuǎn)載自:網(wǎng)絡(luò)轉(zhuǎn)載