将json对象输出为xml文件

一、pom中引入jdom依赖

<dependency>
     <groupId>org.jdom</groupId>
     <artifactId>jdom</artifactId>
     <version>1.1</version>
</dependency>

二、创建xml文件对象

创建的xml文件内容,以及内容对应的json对象如下:

<?xml version="1.0" encoding="UTF-8"?>
<Map version="1.2">
  <name na="名称">法外狂徒</name>
  <attribute att="属性">
    <age ag="年龄">18</age>
    <hobby hob="爱好">
      <one on="之一">woman</one>
      <two tw="之中">youngwoman</two>
    </hobby>
  </attribute>
</Map>

在这里插入图片描述
1.创建xml文件对象

import org.jdom.Document;
import org.jdom.Element;

public static Document getInstanse(){
    
    
        //创建最外层
        Element element = new Element("Map");
        element.setAttribute("version" , "1.2");


        //创建第一层
        Element one_name = new Element("name");     //指定此标签的名称
        one_name.addContent("法外狂徒");    //指定此标签的内容
        one_name.setAttribute("na" , "名称");     //设置此标签的属性

        Element one_attribute = new Element("attribute");
        one_attribute.setAttribute("att" , "属性");


        //创建第二层
        Element two_age = new Element("age");
        two_age.addContent("18");
        two_age.setAttribute("ag" , "年龄");

        Element two_hobby = new Element("hobby");
        two_hobby.setAttribute("hob" , "爱好");


        //创建第三层
        Element three_one = new Element("one");
        three_one.addContent("woman");
        three_one.setAttribute("on" , "之一");

        Element three_two = new Element("two");
        three_two.addContent("youngwoman");
        three_two.setAttribute("tw" , "之中");

        //第二层吃第三层
        two_hobby.addContent(three_one);
        two_hobby.addContent(three_two);

        //第一层吃第二层
        one_attribute.addContent(two_age);
        one_attribute.addContent(two_hobby);

        //最外层吃第一层
        element.addContent(one_name);
        element.addContent(one_attribute);

        return new Document(element);
    }

2.将xml文件对象输出为xml文件

import org.jdom.Document;
import org.jdom.output.Format;
import org.jdom.output.XMLOutputter;

public static void getXmlFile() throws Exception {
    
    
        //获取xml文件对象
        Document document = XmlUtil.getInstanse();

        XMLOutputter xmlOutputter = new XMLOutputter(Format.getPrettyFormat());

        xmlOutputter.output(document , new FileOutputStream("D:\\data\\xml\\abc.xml"));
    }

Guess you like

Origin blog.csdn.net/qq_45697944/article/details/108572252