Skip to content

Java 创建XML

Published: at 00:00
说明
依赖的jar包:
xcerces, xml-api
代码
package me.yhz;

import org.apache.xerces.dom.DocumentImpl;
import org.apache.xerces.dom.ElementNSImpl;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.DOMConfiguration;
import org.w3c.dom.DOMImplementation;
import org.w3c.dom.ls.DOMImplementationLS;
import org.w3c.dom.ls.LSOutput;
import org.w3c.dom.ls.LSSerializer;

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

import java.io.StringWriter;


public class Main {


	public static String toString(Document doc) {
		DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
		DocumentBuilder builder = null;
		try {
			dbf.setFeature("http://apache.org/xml/features/validation/schema/normalized-value", false);
			builder = dbf.newDocumentBuilder();
		} catch (ParserConfigurationException e) {
			System.out.println(e.getMessage());
			return null;
		}

		DOMImplementation impl = builder.getDOMImplementation();
		DOMImplementationLS implLs = (DOMImplementationLS) impl;
		LSSerializer serializer = implLs.createLSSerializer();
		DOMConfiguration domConfig = serializer.getDomConfig();
		//更友好的可读格式
		if (domConfig.canSetParameter("format-pretty-print", new Boolean("true"))) {
			domConfig.setParameter("format-pretty-print", new Boolean("true"));
		}
		LSOutput output = implLs.createLSOutput();

		StringWriter strWriter = new StringWriter();
		output.setCharacterStream(strWriter);
		output.setEncoding("UTF-8");

		serializer.write(doc, output);

		return strWriter.toString();
	}

	public static void main(String[] args) {
		String nsUri = "http://yhz.me";
		String ns = "yhz";
		String xsd = "yhz-1.0.xsd";
		String name = "nate";

		Document doc = new DocumentImpl();

		ElementNSImpl body = (ElementNSImpl) doc.createElementNS(nsUri, ns);
		body.setAttribute("xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance");
		body.setAttribute("xsi:schemaLocation", nsUri + " " + xsd);

		Element eleName = doc.createElement("yhz:name");
		eleName.appendChild(doc.createTextNode(name));
		body.appendChild(eleName);

		Element eleFlag = doc.createElement("yhz:flag");
		body.appendChild(eleFlag);

		Element eleOperation = doc.createElement("yhz:operation");
		eleOperation.setAttribute("type", "request");
		body.appendChild(eleOperation);

		doc.appendChild(body);

		String xml = toString(doc);
		System.out.println(xml);

	}
}