Java XML解析和写入结果缺少行

时间:2016-06-08 12:14:29

标签: java xml dom output

您好我想解析一个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

1 个答案:

答案 0 :(得分:0)

尝试使用OutputKeys.INDENT属性,如下所示:

transformer.setOutputProperty(OutputKeys.INDENT, "yes");