我在解析具有数字字符引用(即 )的 XML 文档时遇到问题。我遇到的问题是,在解析文档时, & 被替换为 & (在 ; 之前没有空格),所以我解析的文档将包含 & ;#xA0;。我该如何阻止这种情况发生?我试过使用xmlDoc.setExpandEntityReferences(false)
,但这似乎并没有改变任何东西。
这是我解析文档的代码:
public static Document getXmlDoc(File xmlFile) throws ParserConfigurationException, SAXExeption, IOException {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setIgnoringElementContentWhitespace(true);
factory.setExpandEntityReferences(false);
DocumentBuilder builder = factory.newDocumentBuilder();
return builder.parse(xmlFile);
}
任何帮助将不胜感激。
编辑:
从上面的代码中解析的 XML 被修改,然后写回一个文件。执行此操作的代码如下:
public static File saveXmlDoc(Document xmlDocument, String outputToDir, String outputFilename) throws IOException {
String outputDir = outputToDir;
if (!outputDir.endWith(File.separator)) outputDir += File.separator;
if (!new FIle(outputDir).exists()) new File(outputDir).mkdir();
File xmlFile = new File(outputDir + outputFilename);
Transformer transformer = TransformerFactory.newInstance().newTransformer();
transformer.setOutputProperty(OutputKeys.INDENT, "no");
StreamResult saveResult = new StreamResult(outputDir + outputFilename);
DOMSource source = new DOMSource(xmlDocument);
transformer.transform(source, saveResult);
return xmlFile;
}
编辑2:
修正了一个错字factory.setIgnoringElementContentWhitespace(true);
。
编辑 3 - 我的解决方案:
由于我的声誉太低而无法回答我自己的问题,因此这是我用来解决所有这些问题的解决方案。
以下是我为解决此问题而更改的功能:
要获取 XML 文档:
public static Document getXmlDoc(File xmlFile) throws ParserConfigurationException, SAXException, IOException {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setIgnoringElementContentWhitespace(true);
factory.setExpandEntityReferences(false);
DocumentBuilder builder = factory.newDocumentBuilder();
return builder.parse(xmlFile);
}
要保存 XML 文档:
public static File saveXmlDoc(Document xmlDocument, String outputToDir, String outputFilename) throws Exception {
readNodesForHexConversion(xmlDocument.getChildNodes());
String xml = getXmlAsString(xmlDocument);
// write the xml out to a file
Exception writeError = null;
File xmlFile = null;
FileOutputStream fos = null;
try {
if (!new File(outputToDir).exists()) new File(outputToDir).mkdir();
xmlFile = new File(outputToDir + outputFilename);
if (!xmlFile.exists()) xmlFile.createNewFile();
fos = new FileOutputStream(xmlFile);
byte[] xmlBytes = xml.getBytes("UTF-8");
fos.write(xmlBytes);
fos.flush();
} catch (Exception ex) {
ex.printStackTrace();
writeError = ex;
} finally {
if (fos != null) fos.close();
if (writeError != null) throw writeError;
}
return xmlFile;
}
要将 XML 文档转换为字符串:
public static String getXmlAsString(Document xmlDocument) throws TransformerFactoryConfigurationError, TransformerException {
DOMSource domSource = new DOMSource(xmlDocument);
StringWriter writer = new StringWriter();
StreamResult result = new StreamResult(writer);
Transformer transformer;
transformer = TransformerFactory.newInstance().newTransformer();
transformer.transform(domSource, result);
return writer.toString();
}