如何在Java中创建具有特定结构的XML文件 [英] How to create XML file with specific structure in Java
本文介绍了如何在Java中创建具有特定结构的XML文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想使用 Java
创建 XML
文件。
我的 XML
文件结构:
<?xml version="1.0" encoding="UTF-8"?>
<CONFIGURATION>
<BROWSER>chrome</BROWSER>
<BASE>http:fut</BASE>
<ENVIRONMENT>abcd</ENVIRONMENT>
<USER>john</USER>
<PASSWORD>abcd123</PASSWORD>
<ORGANIZATION>Tim</ORGANIZATION>
<EMPLOYEE>
<EMP_NAME>Anhorn, Irene</EMP_NAME>
<ACT_DATE>20131201</ACT_DATE>
<DATE_IN>20131201</DATE_IN>
<CLOCK_IN>0800</CLOCK_IN>
<DATE_OUT>20131201</DATE_OUT>
<CLOCK_OUT>1600</CLOCK_OUT>
</EMPLOYEE>
<EMPLOYEE>
<EMP_NAME>Arlegui, Karen Jay</EMP_NAME>
<ACT_DATE>20131201</ACT_DATE>
<DATE_IN>20131201</DATE_IN>
<CLOCK_IN>1600</CLOCK_IN>
<DATE_OUT>20131202</DATE_OUT>
<CLOCK_OUT>0000</CLOCK_OUT>
</EMPLOYEE>
</CONFIGURATION>
推荐答案
您可以使用 Java中的JDOM 库。
将您的代码定义为元素对象,记录您的使用文档类的元素,并使用 SAXBuilder 。试试这个例子:
You can use the JDOM library in Java. Define your tags as Element objects, document your elements with Document Class, and build your xml file with SAXBuilder. Try this example:
Element root=new Element("CONFIGURATION");
Document doc=new Document();
Element child1=new Element("BROWSER");
child1.addContent("chrome");
Element child2=new Element("BASE");
child1.addContent("http:fut");
Element child3=new Element("EMPLOYEE");
child3.addContent(new Element("EMP_NAME").addContent("Anhorn, Irene"));
root.addContent(child1);
root.addContent(child2);
root.addContent(child3);
doc.setRootElement(root);
XMLOutputter outter=new XMLOutputter();
outter.setFormat(Format.getPrettyFormat());
outter.output(doc, new FileWriter(new File("myxml.xml")));
这篇关于如何在Java中创建具有特定结构的XML文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文