、私はこのように始まるXMLファイルの一部を変更する:Javaで解析する際に、文書要素の前に空白を入れる方法は?私のアプリケーションで
<?xml version="1.0" encoding="UTF-8"?>
<!-- $Id: version control yadda-yadda $ -->
<myElement>
...
は<myElement>
の前に空白行を注意してください。ロード後、変更し、保存し、結果ははるかに楽しいからです:
<?xml version="1.0" encoding="UTF-8"?>
<!-- $Id: version control yadda-yadda $ --><myElement>
...
私はコメントとドキュメントノード間の空白(1改行)は、全てのDOMで表現されていないことが判明しました。次の自己完結型コードは、問題を確実に再現します。
String source =
"<?xml version=\"1.0\" encoding=\"UTF-16\"?>\n<!-- foo -->\n<empty/>";
byte[] sourceBytes = source.getBytes("UTF-16");
DocumentBuilder builder =
DocumentBuilderFactory.newInstance().newDocumentBuilder();
Document doc =
builder.parse(new ByteInputStream(sourceBytes, sourceBytes.length));
DOMImplementationLS domImplementation =
(DOMImplementationLS) doc.getImplementation();
LSSerializer lsSerializer = domImplementation.createLSSerializer();
System.out.println(lsSerializer.writeToString(doc));
// output: <?xml version="1.0" encoding="UTF-16"?>\n<!-- foo --><empty/>
これを回避する方法を知っている人はいますか?基本的には、出力を入力と同じにします。 (XML宣言はDOMの一部ではないので再生成されますが、ここで問題にはなりません)
" - ><"の最初の出現を探し、2つの改行を追加するカスタムOutputStreamクラスを使用して、これを出力にハッキングしました。最初のドキュメントの子ノードが実際にコメントになっている場合にのみ、このストリームを使用します。まだハックですが、少なくともきちんとカプセル化されています:-) –
私は同じ問題があります。お助けください。 http://stackoverflow.com/questions/30940162/dom-parser-wrong-childnodes-count – user3930361