用JDOM完成Java更新XML文件
【51CTO快譯】51CTO曾經(jīng)為大家介紹過(guò)“用JDOM整合Java和XML"、“詳解Java解析XML的四種方法”和“JSP實(shí)現(xiàn)JDOM處理數(shù)據(jù)庫(kù)到XML轉(zhuǎn)換的應(yīng)用”。本文詳細(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
- <root>
- <firsttag tag="file">
- <firstsubtag>first subtag</firstsubtag>
- </firsttag>
- <secondtag>second tag</secondtag>
- </root>
下面的Java代碼用于更新或修改一個(gè)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文件。
sample.xml(Modified)
- <root>
- <firsttag tag="test">
- <firstsubtag>This is the first sub tag</firstsubtag>
- </firsttag>
- <secondtag>This is the second tag</secondtag>
- </root>
本文提供了一個(gè)JDOM用簡(jiǎn)單的Java程序來(lái)修改XML文件的方法。51CT0希望這篇文章能對(duì)大家有所幫助。
原文地址:techbrainwave.com/?p=391
原文名:Java code to update an XML file using JDOM
【51CTO譯稿,非經(jīng)授權(quán)謝絕轉(zhuǎn)載,合作媒體轉(zhuǎn)載請(qǐng)注明原文出處及作者!】
【編輯推薦】