Dom4J创建XML

说明:本文主要是用dom4j来创建一个带循环的xml,也是工作中用到的,在此留一个备份吧,关于XML的解析和dom4j的JAR参考http://dycsos123ok.iteye.com/blog/1672870

 

【样式XML】

<gt:XMLReturnTest xmlns:gt="http://www.sgcc.com.cn/sggis/service/schema"
	xmlns:gml="http://www.opengis.net/gml">
	<gt:RecordArray>
		<gt:Record>
			<gt:Field>
				<gt:Name>PSRType</gt:Name>
				<gt:Value>剥皮</gt:Value>
			</gt:Field>
		</gt:Record>
		<gt:Record>
			<gt:Field>
				<gt:Name>PSRType</gt:Name>
				<gt:Value>平儿</gt:Value>
			</gt:Field>
		</gt:Record>
		<gt:Record>
			<gt:Field>
				<gt:Name>PSRType</gt:Name>
				<gt:Value>龙虾妹</gt:Value>
			</gt:Field>
		</gt:Record>
		<gt:Record>
			<gt:Field>
				<gt:Name>PSRType</gt:Name>
				<gt:Value>大婶</gt:Value>
			</gt:Field>
		</gt:Record>
	</gt:RecordArray>
</gt:XMLReturnTest>
 

 

【解析源码】

 

package com.dyc.dom4j;

import java.util.ArrayList;
import java.util.List;

import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;

public class CreateXmlFromDom4J {

	/**
	 * @param args
	 */
	public static final String SGGIS_SCHEMA_PREFIX = "gt";
	public static final String SGGIS_SCHEMA_URI = "http://www.sgcc.com.cn/sggis/service/schema";
	public static final String SGGIS_SCHEMA_PREFIX_GML = "gml";
	public static final String SGGIS_SCHEMA_URI_GML = "http://www.opengis.net/gml";

	public String addListToXML(List<String> list, String rootName) {
		Document doc = DocumentHelper.createDocument();
		Element root = doc.addElement(SGGIS_SCHEMA_PREFIX + ":" + rootName);
		root.addNamespace(SGGIS_SCHEMA_PREFIX, SGGIS_SCHEMA_URI).addNamespace(
				SGGIS_SCHEMA_PREFIX_GML, SGGIS_SCHEMA_URI_GML);
		Element element = root.addElement(SGGIS_SCHEMA_PREFIX + ":RecordArray");
		for (String value : list) {
			Element paramElement = element.addElement(SGGIS_SCHEMA_PREFIX
					+ ":Record");
			Element clildElement1 = paramElement.addElement(SGGIS_SCHEMA_PREFIX
					+ ":Field");
			clildElement1.addElement(SGGIS_SCHEMA_PREFIX + ":Name").addText(
					"PSRType");
			clildElement1.addElement(SGGIS_SCHEMA_PREFIX + ":Value").addText(
					value);
		}
		return root.asXML();
	}

	public static void main(String[] args) {
		List<String> list = new ArrayList<String>() ;
		list.add("剥皮") ;
		list.add("平儿") ;
		list.add("龙虾妹") ;
		list.add("大婶") ;
		CreateXmlFromDom4J cxf = new CreateXmlFromDom4J() ;
		String res = cxf.addListToXML(list, "XMLReturnTest") ;
		System.out.println(res);
	}
}
 

你可能感兴趣的:(java,xml,dom4j)