轉(zhuǎn)帖|其它|編輯:郝浩|2010-06-25 11:09:54.000|閱讀 1598 次
概述:利用JDOM來完成Java代碼對XML文件的更新。本文51CTO轉(zhuǎn)載自外文博客“Tech Brainwave”的一篇技術(shù)文章。詳細(xì)介紹如何利用JDOM來完成Java代碼對XML文件的更新。
# 界面/圖表報表/文檔/IDE等千款熱門軟控件火熱銷售中 >>
本文詳細(xì)介紹Java的文檔對象模型——JDOM(Java Document Object Model)提供了一個完整的用于訪問基于Java的解決方案,JDOM是用Java代碼控制、輸出XML數(shù)據(jù)來完成這項工作的。在JDOM上明確規(guī)定了使用一個Java代碼如何修改XML文檔。我們首先需要下載JDOM的壓縮文件并添加到項目庫文件夾中,下面是對XML文件進(jìn)行修改:
sample.xml
<root>
<firsttag tag="file">
<firstsubtag>first subtag</firstsubtag>
</firsttag>
<secondtag>second tag</secondtag>
</root>
下面的Java代碼用于更新或修改一個XML文件。
import java.io.File;
import java.io.FileWriter;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.input.SAXBuilder;
import org.jdom.output.XMLOutputter;
/**
* @author giftsam
*/
public class XMLModifier
{
/**
* This method is used to modify the data's of an XML file
*/
private void modifyXML()
{
try
{
/**
* Initializing the SAXBuilder class
*/
SAXBuilder builder = new SAXBuilder();
String filePath = "E:" + File.separator + "xml" + File.separator +"sample.xml";
System.out.println("File path is: " + filePath);
File file = new File(filePath);
if (file.exists())
{
Document document = (Document) builder.build(file);
/**
* Get the root element from the document class instance and from the root element get all the child elements and
* replace the appropriate values
*/
Element root = document.getRootElement();
Element firstElement = root.getChild("firsttag");
f irstElement.getAttribute("tag").setValue("file");
firstElement.getChild("firstsubelement").setText("test");
Element secondElement = root.getChild("secondtag");
secondElement.setText("This is the second tag");
/**
* Print the modified xml document
*/
String xmlFileData= new XMLOutputter().outputString(document);
System.out.println("Modified XML file is : " + xmlFileData);
/**
* Modify the orginal document using FileWritter
*/
FileWriter fileWriter = new FileWriter(file);
fileWriter.write(des);
fileWriter.close();
}
else
{
System.out.println("File does not exist");
}
}
catch (Exception ex)
{
ex.printStackTrace();
}
}
public static void main(String argS[])
{
try
{
new XMLModifier().modifyXML();
}
catch (Exception ex)
{
ex.printStackTrace();
}
}
}
下面的是修改后的XML文件。
|
本文提供了一個JDOM用簡單的Java程序來修改XML文件的方法。希望這篇文章能對大家有所幫助。
本站文章除注明轉(zhuǎn)載外,均為本站原創(chuàng)或翻譯。歡迎任何形式的轉(zhuǎn)載,但請務(wù)必注明出處、不得修改原文相關(guān)鏈接,如果存在內(nèi)容上的異議請郵件反饋至chenjj@fc6vip.cn
文章轉(zhuǎn)載自:網(wǎng)絡(luò)轉(zhuǎn)載