熱點推薦:
您现在的位置: 電腦知識網 >> 編程 >> Java編程 >> Java核心技術 >> 正文

用JDOM完成Java更新XML文件

2022-06-13   來源: Java核心技術 

  本文詳細介紹Java的文檔對象模型JDOM (Java Document Object Model)提供了一個完整的用於訪問基於Java的解決方案JDOM是用Java代碼控制輸出XML 數據來完成這項工作的在JDOM上明確規定了使用一個Java代碼如何修改XML文檔我們首先需要下載JDOM的壓縮文件並添加到項目庫文件夾中下面是對XML文件進行修改

  samplexml

  <root>

  <firsttag tag=file>

  <firstsubtag>first subtag</firstsubtag>

  </firsttag>

  <secondtag>second tag</secondtag>

  </root>

  

  下面的Java代碼用於更新或修改一個XML 文件

  import javaioFile;

  import javaioFileWriter;

  import orgjdomDocument;

  import orgjdomElement;

  import orgjdominputSAXBuilder;

  import orgjdomoutputXMLOutputter;

  /**

  * @author giftsam

  */

  public class XMLModifier

  {

  /**

  * This method is used to modify the datas of an XML file

  */

  private void modifyXML()

  {

  try

  {

  /**

  * Initializing the SAXBuilder class

  */

  SAXBuilder builder = new SAXBuilder();

  String filePath = E: + Fileseparator + xml + Fileseparator +samplexml;

  Systemoutprintln(File path is: + filePath);

  File file = new File(filePath);

  if (fileexists())

  {

  Document document = (Document) builderbuild(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 = documentgetRootElement();

  Element firstElement = rootgetChild(firsttag);

  f irstElementgetAttribute(tag)setValue(file);

  

  firstElementgetChild(firstsubelement)setText(test);

  Element secondElement = rootgetChild(secondtag);

  secondElementsetText(This is the second tag);

  

  /**

  * Print the modified xml document

  */

  String  xmlFileData= new XMLOutputter()outputString(document);

  Systemoutprintln(Modified XML file is : + xmlFileData);

  

  /**

  * Modify the orginal document using FileWritter

  */

  FileWriter fileWriter = new FileWriter(file);

  fileWriterwrite(des);

  fileWriterclose();

  }

  else

  {

  Systemoutprintln(File does not exist);

  }

  }

  catch (Exception ex)

  {

  exprintStackTrace();

  }

  }

  

  public static void main(String argS[])

  {

  try

  {

  new XMLModifier()modifyXML();

  }

  catch (Exception ex)

  {

  exprintStackTrace();

  }

  }

  }

  下面的是修改後的XML文件

  samplexml(Modified)

  <root>

  <firsttag tag=test>

  <firstsubtag>This is the first sub tag</firstsubtag>

  </firsttag>

  <secondtag>This is the second tag</secondtag>

  </root>

  本文提供了一個JDOM用簡單的Java程序來修改XML文件的方法CT希望這篇文章能對大家有所幫助

  原文名Java code to update an XML file using JDOM


From:http://tw.wingwit.com/Article/program/Java/hx/201311/25809.html
    推薦文章
    Copyright © 2005-2022 電腦知識網 Computer Knowledge   All rights reserved.