【发布时间】:2016-06-08 12:14:29
【问题描述】:
您好,我想解析一个 XML 文件并更新一些节点并将其写回文件。当我这样做时,留置权已被删除。
解析我使用org.w3c.dom库并写回我使用javax.xml.transform。
这是我的输入:
<?xml version="1.0" encoding="utf-8"?>
<?meta name="GENERATOR" content="XML::Smart/1.6.9 Perl/5.014002 [linux]" ?>
<inputs>
<input id="1">value_to_be_edited</input>
</inputs>
这是我的输出:
<?xml version="1.0" encoding="utf-8" standalone="no"?>
<?meta name="GENERATOR" content="XML::Smart/1.6.9 Perl/5.014002 [linux]" ?><inputs>
<input id="1">new_value</input>
</inputs>
我的问题是我不想删除换行符(在<?meta ?> 和<inputs> 之间),我不想添加standalone="no"。
这是我的代码:
DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
Document doc = docBuilder.parse(file);
... Here I edit the doc ...
TransformerFactory transFactory = TransformerFactory.newInstance();
Transformer transformer = transFactory.newTransformer();
// getIndentationSize() => this function send back the current indentation size of the file
transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", String.valueOf(getIndentationSize()));
// isDeclarationPresent() => say if the <?xml ... ?> declaration was already there or not
transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, (isDeclarationPresent()?"no":"yes"));
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
DOMSource source = new DOMSource(doc);
StreamResult result = new StreamResult(file);
transformer.transform(source, result);
对不起我的英语,我是法国人。 BR
【问题讨论】:
-
这种问题总是很棘手。你不应该想要你所问的。 XML 规范说您实际得到的和您想要的都是相同的 XML 文档(它们看起来相同,但它们意思相同)。因此,实现您想要的意味着与 XML 实现作斗争,以使它们做他们不知道的事情。他们没有办法实现你想要的,因为他们已经是(从规范上讲)。所以你可能会找到一种方法让它做你想做的事......但你不应该这样做。换句话说:你确定你的期望吗?
-
@GPI 感谢您的回答,我不知道它们与 XML 规范中的相同。对于我的第二个问题,关于
standalone="no",我尝试了transformer.setOutputProperty(OutputKeys.STANDALONE, "yes");,但它没有做任何事情,你有什么想法吗?