后端工程师写xml文件,Java还是groovy?

对于Java程序员来说,用Java语言生成xml文件,是异常复杂的。
先举例java 的三种写xml文件方法,然后给出最简单的实现方式:利用groovy语言生成。大家可以对比一下。

一、Dom写入

// 创建解析器工厂			
			DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
			DocumentBuilder db = factory.newDocumentBuilder();
			Document document = db.newDocument();
			// 不显示standalone="no"
			document.setXmlStandalone(true);
			Element bookstore = document.createElement("bookstore");
			// 向bookstore根节点中添加子节点book
			Element book = document.createElement("book");
			//.....
			// 创建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("book1.xml")));
			System.out.println("生成book1.xml成功");

二、Dom4j写入

			// 1、创建document对象
			Document document = DocumentHelper.createDocument();
			// 2、创建根节点rss
			Element rss = document.addElement("rss");
			// 3、向rss节点添加version属性
			rss.addAttribute("version", "2.0");
			// 4、生成子节点及子节点内容
			Element channel = rss.addElement("channel");
			Element title = channel.addElement("title");
			//.....
			// 6、生成xml文件			
			File file = new File("rss.xml");
			XMLWriter writer = new XMLWriter(new FileOutputStream(file), format);
			// 设置是否转义,默认使用转义字符
			writer.setEscapeText(false);
			writer.write(document);
			writer.close();


三、jDom写入

public static void createXml(){
		try {
			// 1、生成一个根节点
			Element rss = new Element("rss");
			// 2、为节点添加属性
			rss.setAttribute("version", "2.0");			
			// 3、生成一个document对象
			Document document = new Document(rss);
			
			Element channel = new Element("channel");
			rss.addContent(channel);
			Element title = new Element("title");
			title.setText("国内最新新闻");
			channel.addContent(title);
						
			Format format = Format.getCompactFormat();
			// 设置换行Tab或空格
			format.setIndent("	");
			format.setEncoding("UTF-8");
						
			// 4、创建XMLOutputter的对象
			XMLOutputter outputer = new XMLOutputter(format);
			// 5、利用outputer将document转换成xml文档
			File file = new File("rssNew.xml");
			outputer.output(document, new FileOutputStream(file));

			System.out.println("生成rssNew.xml成功");
		} catch (Exception e) {
			System.out.println("生成rssNew.xml失败");
		}
	}

四、利用groovy生成

1)引入pom

 <dependency>
            <groupId>org.codehaus.groovy</groupId>
            <artifactId>groovy-all</artifactId>
            <version>2.5.7</version>
            <type>pom</type>
            <exclusions>
                <exclusion>
                    <groupId>org.codehaus.groovy</groupId>
                    <artifactId>groovy-test</artifactId>
                </exclusion>

                <exclusion>
                    <groupId>org.codehaus.groovy</groupId>
                    <artifactId>groovy-test-junit5</artifactId>
                </exclusion>
                <exclusion>
                    <groupId>org.codehaus.groovy</groupId>
                    <artifactId>groovy-testng</artifactId>
                </exclusion>
            </exclusions>
        </dependency>

2)新建groovy文件,代码实现

public class FileTransferDescription {

    public void genFileTransferComplete(String path,String xmlName){
        def strXml = new StringWriter()
        MarkupBuilder mb = new MarkupBuilder(strXml)
        mb.mkp.xmlDeclaration(version: "1.0", encoding: "utf-8")
        mb.InterfaceFile {
            FileHeader{
                messageType("messageType")
                messageID("0001")  
            }
            FileBody{
                fileList{
                    fileName("123.dat")
                    filePath("/home/data/")
                }
            }
        }
        writeXml(path, xmlName, strXml.toString())
    }

    private void writeXml(String absolutePath, String metafilename, String strXml) {
        print(strXml)
        FileWriter fileWriter = new FileWriter(new File(absolutePath + metafilename))
        fileWriter.write(strXml)
        fileWriter.flush()
        fileWriter.close()
    }

    public static void main(String[] args) {
        FileTransferDescription fileTransferDescription = new FileTransferDescription();
        fileTransferDescription.genFileTransferComplete("E:\\testpath1\\","test.xml");
    }

在这里插入图片描述
实现代码是不是很简洁易懂?
Java实现方法引用了3y先生的文章Java生成xml文件的四种方式。
添加链接描述

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值