用java怎么创建xml文件_Java 创建XML文件

package cn.jbolt.writefile;

import java.io.File;

import java.util.Arrays;

import java.util.List;

import javax.xml.parsers.DocumentBuilder;

import javax.xml.parsers.DocumentBuilderFactory;

import javax.xml.transform.OutputKeys;

import javax.xml.transform.Transformer;

import javax.xml.transform.TransformerFactory;

import javax.xml.transform.dom.DOMSource;

import javax.xml.transform.stream.StreamResult;

import org.w3c.dom.Document;

import org.w3c.dom.Element;

public class CreateXML {

private static final String xmlPath = "F:\\demo.xml";

public static void main(String[] args) {

createXml(xmlPath);

}

/**

* 生成xml方法

*/

public static void createXml(String xmlPath) {

try {

// 创建解析器工厂

DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();

DocumentBuilder domBuilder = factory.newDocumentBuilder();

Document document = domBuilder.newDocument();

// 不显示standalone="no"

document.setXmlStandalone(true);

Element bookstore = document.createElement("folder");

String [] demo = new String[2];

List dataList = Arrays.asList(demo);

dataList.forEach(action ->{

Element file = document.createElement("file");

Element num = document.createElement("num");

num.setTextContent("1");

//其他方法请自行 . 出来

Element no = document.createElement("no");

no.setTextContent("档号");

Element responsible = document.createElement("responsible");

Element title = document.createElement("title");

Element date = document.createElement("date");

Element classification = document.createElement("classification");

Element electronicName = document.createElement("electronicName");

Element note = document.createElement("note");

file.appendChild(num);

file.appendChild(no);

file.appendChild(responsible);

file.appendChild(title);

file.appendChild(date);

file.appendChild(classification);

file.appendChild(electronicName);

file.appendChild(note);

bookstore.appendChild(file);

});

document.appendChild(bookstore);

// 创建TransformerFactory对象

TransformerFactory tff = TransformerFactory.newInstance();

// 创建 Transformer对象

Transformer tf = tff.newTransformer();

// 输出内容是否使用换行

tf.setOutputProperty(OutputKeys.INDENT, "yes");

// 创建xml文件并写入内容

tf.transform(new DOMSource(document), new StreamResult(new File(xmlPath)));

System.out.println("生成demo.xml成功");

} catch (Exception e) {

e.printStackTrace();

System.out.println("生成demo.xml失败");

}

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值