2016-12-28 3 views
0

を維持しながらJavaは、私は現在、この形式で複数のXMLファイルで構成されたXML文字列(すべてのXMLデータは、文字列のXMLに格納されている)で働いている複数のXMLファイルを含むXML文字列を分割:パターン

<?xml version="1.0" encoding="UTF-8"?> 
<File xml:space="preserve"> 
    <Subfile keyword="Store" tag="0"> 
      <Value number="1">Amazon</Value> 
    </Subfile> 
    <Subfile keyword="Owner" tag="1"> 
      <Value number="1">Alice Murphy</Value> 
    </Subfile> 
    <Subfile keyword="Date" tag="2"> 
      <Value number="1">20161114</Value> 
    </Subfile> 
</File> 

<?xml version="1.0" encoding="UTF-8"?> 
<File xml:space="preserve"> 
    <Subfile keyword="Store" tag="0"> 
      <Value number="1">Walmart</Value> 
    </Subfile> 
    <Subfile keyword="Owner" tag="1"> 
      <Value number="1">Eliza Calvin</Value> 
    </Subfile> 
    <Subfile keyword="Date" tag="2"> 
      <Value number="1">20161130</Value> 
    </Subfile> 
</File> 
... 

私はxmlタグに基づいてString.split()を使ってこのxml文字列を分割したいと思います。

また、結果として配列の要素に、区切り文字として機能するxmlタグを保持したいとします。私が使用し

コードは、私がこれをしなかったときしかし、何事もなかっ

String[] xmls = xmlString.split("(?=<?xml version=\"1.0\" encoding=\"UTF-8\"?>)"); 

ました。私はここで間違って何をしていますか?

ありがとうございました!

+0

あなたは特殊文字をエスケープしていません。 – shmosel

+0

また、*何も起こっていない*非常に有用な問題の説明ではありません。 – shmosel

+1

'Pattern.quote()'を使用してパターンをエスケープする –

答えて

1

?文字の前に\\を追加するだけでエスケープする必要があります。これは、正規表現で何らかの意味を持つすべての特殊文字に対して起こります。したがって、特別な文字を単純な文字列として使用する場合はいつも、\\を接頭辞として使用する必要があります。

次のコードスニペットが機能します。

String separator = "(?=<\\?xml version=\"1.0\" encoding=\"UTF-8\"\\?>)"; 
String[] xmls = xmlString.split(separator); 
for (String xml : xmls) { 
    System.out.println(xml); 
    System.out.println("-----------------------------------"); 
} 

それは印刷されます。

<?xml version="1.0" encoding="UTF-8"?> 
<File xml:space="preserve"> 
    <Subfile keyword="Store" tag="0"> 
      <Value number="1">Amazon</Value> 
    </Subfile> 
    <Subfile keyword="Owner" tag="1"> 
      <Value number="1">Alice Murphy</Value> 
    </Subfile> 
    <Subfile keyword="Date" tag="2"> 
      <Value number="1">20161114</Value> 
    </Subfile> 
</File> 


----------------------------------- 
<?xml version="1.0" encoding="UTF-8"?> 
<File xml:space="preserve"> 
    <Subfile keyword="Store" tag="0"> 
      <Value number="1">Walmart</Value> 
    </Subfile> 
    <Subfile keyword="Owner" tag="1"> 
      <Value number="1">Eliza Calvin</Value> 
    </Subfile> 
    <Subfile keyword="Date" tag="2"> 
      <Value number="1">20161130</Value> 
    </Subfile> 
</File> 
----------------------------------- 

編集:次のように.をエスケープする必要があります。

String separator = "(?=<\\?xml version=\"1\\.0\" encoding=\"UTF-8\"\\?>)"; 

これを指摘してくれた@shmoselに感謝します。

+0

完全に作業しました。それを知ってうれしい "?"この場合は「//」が必要です。ありがとうございました。 – 000000000000000000000

+1

'.'もエスケープする必要があります。 – shmosel

+0

@shmoselあなたは正しいですが、 '.'も特殊文字です。 '.'は引用符の間にあるので、おそらく私のコードが動作しています!確かに。 –