1 package com.zznode.transmit.util; 2 3 import java.io.File; 4 import java.io.FileInputStream; 5 import java.io.InputStreamReader; 6 import java.io.Reader; 7 import java.util.Iterator; 8 9 import org.dom4j.Document; 10 import org.dom4j.Element; 11 import org.dom4j.QName; 12 import org.dom4j.io.SAXReader; 13 14 public class XMLParseUtil { 15 16 /** 17 * 解析CmFile->Objects->FieldValue xml文件 18 * @param fileName 19 * @return xxxx&#&xxxx&#&xxxx&#&###&&&###xxxx&#&xxxx&#&xxxx&#&的字符串 20 */ 21 public static String parseXML(String fileName, String encoding) { 22 SAXReader sax = new SAXReader(); 23 Document doc = null; 24 25 StringBuilder strBuilder = new StringBuilder(); 26 27 try { 28 File file = new File(fileName); 29 FileInputStream in = new FileInputStream(file); 30 Reader r = new InputStreamReader(in); 31 32 doc = sax.read(r); 33 Element objects = doc.getRootElement() 34 .element(new QName("Objects")).element( 35 new QName("FieldValue")); 36 Iterator iter = objects.elementIterator(); 37 while (iter.hasNext()) { 38 Element ele = (Element) iter.next(); 39 Iterator cmIter = ele.elementIterator(); 40 //使用"&#&"作为数据分隔符 41 while (cmIter.hasNext()) { 42 Element vElement = (Element) cmIter.next(); 43 String elementValue = vElement.getStringValue(); 44 if (elementValue == null || elementValue.trim().equals("")) { 45 elementValue = "-"; 46 } 47 //使用"###&&&###"作为记录分割符 48 strBuilder.append(elementValue + "&#&"); 49 } 50 strBuilder.append("###&&&###"); 51 52 } 53 } catch (Exception e) { 54 // TODO Auto-generated catch block 55 e.printStackTrace(); 56 } 57 return strBuilder.toString(); 58 } 59 60 }