Java XML 数字字符引用

标签 java xml xml-parsing

当我解析具有数字字符引用(即  )的 XML 文档时遇到问题。我遇到的问题是,当解析文档时, & 被替换为 & (; 之前没有空格),因此我解析的文档将包含  。我该如何阻止这种情况发生?我尝试过使用 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();
}

最佳答案

我目前无法重现该问题。这是一个简短但完整的程序,它试图:

import org.w3c.dom.*;
import java.io.*;
import javax.xml.*;
import javax.xml.parsers.*;

public class Test {
    public static void main (String[] args) throws Exception {
        byte[] xml = "<foo>&#xA0;</foo>".getBytes("UTF-8");
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        factory.setIgnoringElementContentWhitespace(true);
        factory.setExpandEntityReferences(false);
        DocumentBuilder builder = factory.newDocumentBuilder();
        Document document = builder.parse(new ByteArrayInputStream(xml));
        Element element = document.getDocumentElement();
        String text = element.getFirstChild().getNodeValue();
        System.out.println(text.length()); // Prints 1
        System.out.println((int) text.charAt(0)); // Prints 160
    }
}

现在还不清楚上面的 XML 是否会再次写出 - 如果您显示用于执行此操作的代码将会有所帮助 - 但很明显,文本节点的单字符值是被读作“&”符号后跟“#xA0;”分开,因为我相信你的问题描述了它,所以我真的很惊讶地看到它写成“ ”。

你能写一个类似的简短但完整的程序来演示这个问题吗?我自己会继续尝试这样做。

关于Java XML 数字字符引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13200297/

相关文章:

java - Java ESAPI 中的编码

c++ - PugiXML C++ 换行符处理问题 : '\n\n' becomes '\\n\\n'

java - 为独立应用程序绑定(bind)一个 java swing gui 和 c++ 后端,它们形成两个不同的项目

Java - 如何制作 JButton "Deselected"

php - 从 PHP 创建 XML 文件但得到 HTML 文件

.net - xmlns 元素的顺序是否重要

java - 将 xml 数据导入 sql 数据库的语法 - 逐行

java - 如何从 FilteredReader 中获取 XML 文档?

java - 循环遍历所有节点并更新Java中的值

java - 为什么在 Controller 中使用 @GetMapping 而不是 @DeleteMapping 进行删除工作?