繁体   English   中英

Java API编码特殊的XML字符?

[英]Java API to encode special XML characters?

是否有Java API可以编码XML特殊字符:<,>,&,“,”

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

URLEncode对所有内容(包括空格)进行编码,因此无法使用。

谢谢

如果从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/

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM