xml 导出

本文介绍了一种使用Java实现的解析XML文件并将其内容转换为结构化数据的方法,包括创建XML文档、解析XML元素以及将数据结构化存储到Map中。最后,该方法将结构化数据导出为XML文件。
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.jdom.output.Format;
import org.jdom.output.XMLOutputter;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

public class ParseXML {

/**
*
* @param infomation 资料信息
* @return 资料文件名称 ,资料文件路径
* @throws FileNotFoundException
*/
@SuppressWarnings("unchecked")
public Map<String, String> infomationExport(List<Map<String, String>> infomation) {
//创建根节点
org.jdom.Element root = new org.jdom.Element("infomationList");

//创建doc解析对象
org.jdom.Document document = new org.jdom.Document(root);
//迭代所有资料信息
for (Iterator iterator = infomation.iterator(); iterator.hasNext();) {
Map<String, String> map = (Map<String, String>) iterator.next();
org.jdom.Element elements = new org.jdom.Element("infomation");
//迭代第一行资料信息
for (Iterator iterator2 = map.entrySet().iterator(); iterator2.hasNext();) {
Map.Entry<String, String> rowMap = (Map.Entry<String, String>) iterator2.next();
if(null == rowMap.getKey())
{
elements.addContent( new org.jdom.Element("templateTag").setText(rowMap.getValue()));
}
else{
elements.addContent( new org.jdom.Element(rowMap.getKey()).setText(rowMap.getValue()));
}
}
root.addContent(elements);
}
//xml输出解析器
XMLOutputter output = new XMLOutputter(Format.getPrettyFormat());
//导出文件模板
File file = new File(“/templateXml.xml”);
OutputStream outStream;
try {
outStream = new FileOutputStream(file);
output.output(document, outStream);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
//存储文件名称,文件路径的容器
Map<String,String> fileMap = new HashMap<String,String>();
fileMap.put(file.getName(), file.getAbsolutePath());
return fileMap;
}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值