本文详细介绍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