我有一个来自网络 API 的 XML 文件输入。当我尝试从浏览器将其另存为 XML 文件时,其中有一些多余的
。问题是,当尝试通过 StaX 解析此 XML 数据并在处理后执行某些任务写回另一种 XML 格式(如 DOM)时,它会出现
。
我想做的就是避免输入中多余的
和输出中的
。
无法找到这些背后的原因,也没有明确的解决方案。
这是保存到文件后我在输入 XML 元素值中得到的内容,
Today is a fine day.
 
 So does everyday.
写入后,输出
Today is a fine day. So does everyday.
实际上预期和要求的输出
<someNode>Today is a fine day.
So does everyday.
</someNode>
节点的 Text 值中的新行是故意的,需要按原样保留。
简化的代码示例:
从 API 读取流:
// Get Input XML stream from API
URL apiURL = new URL(API_Url);
HttpsURLConnection httpsAPIURLConn;
httpsAPIURLConn = (HttpsURLConnection) apiURL.openConnection();
httpsAPIURLConn.setConnectTimeout(10000); // timeout
httpsAPIURLConn.setDoInput(true);
InputStream inStream = httpsAPIURLConn.getInputStream();
// Data stream okay, Start StaX XLIFF reader
XMLInputFactory xmlInputFactory = XMLInputFactory.newInstance();
// This is to read entity referenced strings
xmlInputFactory.setProperty(XMLInputFactory.IS_COALESCING, true);
// StaX StreamReader
XMLStreamReader xmlStreamReader = xmlInputFactory.createXMLStreamReader(new BufferedInputStream(inStream), "UTF-8");
// Read and load XML data to in-memory database to filter and process
写入原始数据过滤处理后生成新的XML结构文件
// After processing and writing new Element structure to org.w3c.dom.Document
// write the content into xml file
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer tr = transformerFactory.newTransformer();
tr.setOutputProperty(OutputKeys.INDENT, "yes");
tr.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
tr.setOutputProperty(OutputKeys.METHOD, "xml");
tr.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
tr.setOutputProperty(OutputKeys.STANDALONE, "no");
DOMSource source = new DOMSource(doc);
File file = new File(xmlFilePath);
Writer outputStream = new OutputStreamWriter(new FileOutputStream(file), "UTF-8");
StreamResult result = new StreamResult(outputStream);
tr.transform(source, result);
不确定我到底错过了什么。但任何建议或帮助都会很棒。
最佳答案
最简单的解决方案(除了挂接到 SAX 事件流之外)是编写一个完全满足您需要的 XSLT 脚本,并将其调用为您的转换器而不是默认的身份转换器。
参见http://en.wikipedia.org/wiki/Identity_transform#Using_XSLT寻求建议。
然后,您需要提供自己的文本节点转换规则,通过将 ASCII 13 字符转换为空字符串来删除它们。请参阅https://stackoverflow.com/a/5084382/53897了解详情。
关于java - #xD;和#13;读写 XML 文件时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24737918/