码迷,mamicode.com
首页 > 编程语言 > 详细

JAVA生成XML文件

时间:2017-07-31 14:29:52      阅读:161      评论:0      收藏:0      [点我收藏+]

标签:nbsp   print   调用   leo   sed   closed   code   throw   ide   

由于工作需要,需要生成如下xml:

技术分享
<?xml version="1.0" encoding="UTF-8"?>

<root>
<Scorm Theme="2016-06-22 18:09:45" Speakor="" Introduction="" ScromType="1">
<VideoList Name="通道1" Count="1">
<Video File="111.mp4" Time="118000"/>
</VideoList>
<VideoList Name="通道2" Count="1">
<Video File="222.mp4" Time="118000"/>
</VideoList>
<IndexList Count="0"/>
<ChangeList Count="0"/>
</Scorm>
</root>
View Code

编写方法如下:

技术分享
public void creatXML(String path, String[] names, String[] timelengths)
            throws IOException {
        path = path + "\\assets\\";
        Document doc = DocumentHelper.createDocument();
        // 增加根节点
        Element root = doc.addElement("root");
        // 增加子元素
        Element scorm = root.addElement("Scorm");
        // 为子节点添加属性
        scorm.addAttribute("theme", "");
        scorm.addAttribute("speakor", "");
        scorm.addAttribute("introduction", "");
        scorm.addAttribute("ScromType", "1");
        for (int i = 0; i < names.length; i++) {
            String name = names[i].substring(names[i].lastIndexOf("\\") + 1,
                    names[i].length());
            Element videoList = scorm.addElement("VideoList");
            videoList.addAttribute("Name", "通道" + (i + 1));
            videoList.addAttribute("Count", "1");
            Element video = videoList.addElement("Video");
            video.addAttribute("File", name);
            video.addAttribute("Time", timelengths[i]);
        }
        Element indexList = scorm.addElement("IndexList");
        indexList.addAttribute("Count", "0");
        Element changeList = scorm.addElement("ChangeList");
        changeList.addAttribute("Count", "0");
        // 实例化输出格式对象
        OutputFormat format = OutputFormat.createPrettyPrint();
        // 设置输出编码
        format.setEncoding("UTF-8");
        // 创建需要写入的File对象
        File file = new File(path + File.separator + "videoList.xml");
        // 生成XMLWriter对象,构造函数中的参数为需要输出的文件流和格式
        XMLWriter writer = new XMLWriter(new FileOutputStream(file), format);
        // 开始写入,write方法中包含上面创建的Document对象
        writer.write(doc);
    }
View Code

调用:

技术分享
1 String[] names = {"1通道","2通道","3通道"};
2 String[] timelengths = {"500","500","500"};
3 String path = "E:\\video\\";
4 
5 creatXML(path,names,timelengths);
View Code

 

JAVA生成XML文件

标签:nbsp   print   调用   leo   sed   closed   code   throw   ide   

原文地址:http://www.cnblogs.com/pengpengzhang/p/7262681.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!