Java XML数字字符引用

时间:2012-11-02 17:31:25

标签: java xml xml-parsing

当我解析具有数字字符引用的XML文档(即&#xA0)时,我遇到了问题。我遇到的问题是,当解析文档时,&替换为& amp; (没有前面的空格;),所以我的解析文档将包含& amp;#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();
}

1 个答案:

答案 0 :(得分:1)

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

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;”另外,因为我相信你的问题描述了它,所以我会惊讶地发现它被写成“&amp;#xA0;”。

你能写一个类似的简短而完整的程序 来证明这个问题吗?我会继续尝试这样做。