java xml,创建自闭标签

时间:2016-03-01 05:58:06

标签: java xml xerces

我在java中使用Xerces xml库。

我能够创建一个像:

这样的元素

Element myElement = doc.createElement("element");

会产生<element></element>

我如何创建一个会导致自闭标签的元素呢?

<element/>

感谢。

1 个答案:

答案 0 :(得分:1)

例如,您需要创建类似

的XML
 xml 

<?xml version="1.0" encoding="UTF-8"?>
<RootElement>
   <element />
</RootElement>

我们可以获得如下代码的Java代码片段。

import java.io.StringWriter;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.w3c.dom.Document;
import org.w3c.dom.Element;

public class XmlTransformer{

    public static void main(String args[]) {
        String xml = "";
        try {
            DocumentBuilderFactory docFactory = DocumentBuilderFactory
                    .newInstance();
            DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
            Document doc = docBuilder.newDocument();
            Element rootElement = doc.createElement("RootElement");
            doc.appendChild(rootElement);

            Element myElement = doc.createElement("element");
            rootElement.appendChild(myElement);
            TransformerFactory transformerFactory = TransformerFactory
                    .newInstance();
            Transformer transformer = transformerFactory.newTransformer();
            DOMSource source = new DOMSource(doc);
            StringWriter writer = new StringWriter();
            StreamResult result = new StreamResult(writer);

            transformer.transform(source, result);
            xml = writer.toString();
            System.out.println(" xml \n \n " +xml);
        } catch (ParserConfigurationException pce) {
            pce.printStackTrace();
        } catch (TransformerException tfe) {
            tfe.printStackTrace();
        }
    }

}