- package com.util.xml;
- import java.io.BufferedReader;
- import java.io.File;
- import java.io.FileOutputStream;
- import java.io.FileReader;
- import java.io.IOException;
- import java.util.ArrayList;
- import java.util.HashMap;
- import java.util.Iterator;
- import java.util.List;
- import java.util.Map;
- import org.jdom.Document;
- import org.jdom.Element;
- import org.jdom.output.Format;
- import org.jdom.output.XMLOutputter;
- /**生成xml
- * @author
- * 2013-1-1
- */
- public class XmlHelper {
- private String defultValue="1";
- public void getXmlValue(String filePath) throws IOException{
- //FileInputStream fis = new FileInputStream("D:/ws.txt");
- //BufferedInputStream inputStream = new BufferedInputStream(fis);
- File file = new File("D:/ws.txt");
- BufferedReader bd = new BufferedReader(new FileReader(file));
- Map<String, List<String[]>> valueMap=new HashMap<String,List<String[]>>();
- byte[] block = new byte[512];
- String lineStr = "";
- while ((lineStr = bd.readLine()) != null) {
- // int readLength = inputStream.read(block);
- // if (readLength == -1)
- // break;
- // String str=new String(block,0,readLength);
- String[] strArray = lineStr.split(",");
- List<String[]> strList=null;
- strList=valueMap.get(strArray[2]);
- if(strList==null){
- strList=new ArrayList<String[]>();
- strList.add(strArray);
- valueMap.put(strArray[2], strList);
- }else{
- strList=valueMap.get(strArray[2]);
- strList.add(strArray);
- valueMap.put(strArray[2], strList);
- }
- }
- bd.close();
- BuildXMLDoc(valueMap);
- }
- public void BuildXMLDoc(Map<String, List<String[]>> valueMap) throws IOException{
- // 创建根节点 list;
- List<String[]> rootList=valueMap.get("0");
- String[] rootValue=rootList.get(0);
- String rootStr=rootValue[1];
- Element root = new Element(rootStr);
- List<String[]> sonList=valueMap.get(rootValue[0]);
- root=addElement(root,sonList,valueMap);
- // 根节点添加到文档中;
- Document Doc = new Document(root);
- Format format = Format.getPrettyFormat();
- XMLOutputter XMLOut = new XMLOutputter(format);
- // 输出xml文件;
- XMLOut.output(Doc, new FileOutputStream("D:\\\\creatXml.xml"));
- }
- public Element addElement(Element root,List<String[]> sonList,Map<String, List<String[]>> valueMap){
- if(sonList!=null){
- for (Iterator iterator = sonList.iterator(); iterator.hasNext();) {
- String[] Sonstring = (String[]) iterator.next();
- List<String[]> ssonList=valueMap.get(Sonstring[0]);
- if(ssonList!=null){
- Element sonElement=new Element(Sonstring[1]);
- root.addContent(addElement(sonElement,ssonList,valueMap));
- }else{
- Element sonElement=new Element(Sonstring[1]).setText(defultValue);
- root.addContent(sonElement);
- }
- }
- return root;
- }else {
- return root;
- }
- }
- public static void main(String[] args) throws IOException {
- XmlHelper xmlHelper = new XmlHelper();
- xmlHelper.getXmlValue("");
- }
- }
- //该片段来自于http://www.codesnippet.cn/detail/100420149281.html
来源: http://www.codesnippet.cn/detail/100420149281.html