用于编码特殊XML字符的Java API?

时间:2014-09-10 20:48:50

标签: java xml encode

是否有编码XML特殊字符的Java API:<,>,&,“,'

我的代码读取文件并从中创建XML。当我们正在读取文件时,是否有办法在不对它们进行硬编码的情况下转义这些字符?

URLEncode对所有内容进行编码,包括空格,所以我不能使用它。

由于

1 个答案:

答案 0 :(得分:0)

如果您从DOM创建XML,那么特殊字符将被转义。

例如

import java.io.StringWriter;
import java.io.Writer;

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

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

public class NewXML {
public static void main(String[] args) throws Exception {

        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = dbf.newDocumentBuilder();
        Document doc = builder.newDocument();

        // create the root element node
        Element element = doc.createElement("root");
        doc.appendChild(element);

        // create a comment node given the specified string
        Comment comment = doc.createComment("This is a comment");
        doc.insertBefore(comment, element);

        // add element after the first child of the root element
        Element itemElement = doc.createElement("item");
        element.appendChild(itemElement);

        // add an attribute to the node
        itemElement.setAttribute("myattr", "attr>value");

        // create text for the node
        itemElement.insertBefore(doc.createTextNode("te<xt"), itemElement.getLastChild());

        prettyPrint(doc);

    }

    public static final void prettyPrint(Document xml) throws Exception {
        Transformer tf = TransformerFactory.newInstance().newTransformer();
        tf.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
        tf.setOutputProperty(OutputKeys.INDENT, "yes");
        Writer out = new StringWriter();
        tf.transform(new DOMSource(xml), new StreamResult(out));
        System.out.println(out.toString());
    }
}

产生

<?xml version="1.0" encoding="UTF-8"?><!--This is a comment--><root>
<item myattr="attr&gt;value">te&lt;xt</item>
</root>

PS。从此网站提取的示例 - http://examples.javacodegeeks.com/core-java/xml/dom/create-dom-document-from-scratch/