【发布时间】:2016-12-10 19:06:33
【问题描述】:
我从服务器获取任意 XML 并使用以下 Java 代码对其进行解析:
String xmlStr; // arbitrary XML input
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
try {
DocumentBuilder builder = factory.newDocumentBuilder();
InputSource is = new InputSource(new StringReader(xmlStr));
return builder.parse(is);
}
catch (SAXException | IOException | ParserConfigurationException e) {
LOGGER.error("Failed to parse XML.", e);
}
每隔一段时间,XML 输入会包含一些未知实体引用,例如  ,并因错误而失败,例如 org.xml.sax.SAXParseException: The entity "nbsp" was referenced, but not declared.
我可以通过预处理原始xmlStr 并在解析之前翻译所有有问题的实体引用来解决这个问题。这是一个有效的虚拟实现:
protected static String translateEntityReferences(String xml) {
String newXml = xml;
Map<String, String> entityRefs = new HashMap<>();
entityRefs.put(" ", " ");
entityRefs.put("«", "«");
entityRefs.put("»", "»");
// ... and 250 more...
for(Entry<String, String> er : entityRefs.entrySet()) {
newXml = newXml.replace(er.getKey(), er.getValue());
}
return newXml;
}
但是,这真的很不令人满意,因为有are a huge number of entity references,我不想将它们全部硬编码到我的 Java 类中。
是否有任何简单的方法可以将整个字符实体引用列表传授给 DocumentBuilder?
【问题讨论】:
-
看起来很有趣,但我如何说服我的 DocumentBuilder 呢? ;-)
-
你可以试试这个正则表达式用空字符串替换匹配的内容。字符串正则表达式 = "&|#|[A-Za-z]?(\\w+|\\d+);";模式模式 = Pattern.compile(regexe);否则你可以试试 JSOUP 库。检查链接http://stackoverflow.com/questions/36026353/parsing-xml-file-containing-html-entities-in-java-without-changing-the-xml。
-
看起来也是一样的要求。检查它是否对你有帮助。
-
也许真的需要一些正则表达式预处理。但是,我希望将 any 引用翻译成正确的字符(不仅是  ,而且是整个列表......)。我希望 Java 已经有解决方案了……
标签: java xml parsing xml-parsing