我有一个Java XML实用程序类。 buildDocument()
方法接受XML字符串并返回org.w3c.dom.Document
。我传递给它的特定XML是一个xhtml 1.1文档。
问题在于是否存在HTML命名实体,如
<p>Preserve dagger †</p>
输出是,
<p>Preserve dagger </p>
确实保留了<
,>
,&
,"
。
以下是创建Document
的课程。
package com.example;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.StringWriter;
import java.nio.charset.StandardCharsets;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
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.Document;
import org.xml.sax.SAXException;
public final class XMLUtils {
private XMLUtils() {
}
public static Document buildDocument(String xml) throws ParserConfigurationException, SAXException, IOException {
DocumentBuilderFactory domFactory = DocumentBuilderFactory
.newInstance();
domFactory.setNamespaceAware(true);
domFactory.setFeature("http://xml.org/sax/features/validation", false);
domFactory.setFeature(
"http://apache.org/xml/features/nonvalidating/load-dtd-grammar", false);
domFactory.setFeature(
"http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
domFactory.setCoalescing(false);
DocumentBuilder builder = domFactory.newDocumentBuilder();
Document doc = builder.parse(new ByteArrayInputStream(
xml.getBytes(StandardCharsets.UTF_8)));
try {
DOMSource domSource = new DOMSource(doc);
StringWriter writer = new StringWriter();
StreamResult result = new StreamResult(writer);
TransformerFactory tf = TransformerFactory.newInstance();
Transformer transformer = tf.newTransformer();
transformer.transform(domSource, result);
System.out.println("XML OUT: \n" + writer.toString());
} catch (Exception ex) {
}
return doc;
}
}
我认为这些是相关的依赖。
<dependency>
<groupId>net.sf.saxon</groupId>
<artifactId>Saxon-HE</artifactId>
<version>9.5.1-6</version>
</dependency>
<dependency>
<groupId>xerces</groupId>
<artifactId>xercesImpl</artifactId>
<version>2.11.0</version>
<type>jar</type>
</dependency>
<dependency>
<groupId>xml-resolver</groupId>
<artifactId>xml-resolver</artifactId>
<version>1.2</version>
<type>jar</type>
</dependency>
有关如何保存这些实体的任何想法?谢谢,/ w
答案 0 :(得分:0)
花了一些时间才找到这个问题的解决方案,显然很难找到合适的关键字...因为我发现这个之前找到了最好的答案,我认为是值得在这里链接它,即使它仍然在StackOverflow上。你去:Keep numeric character entity characters such as ` ` when parsing XML in Java
这不太令人满意,但至少它解释了为什么没有更好的解决方案。