2016-03-28 6 views
1

私はxmlファイルを持っていますが、時にはいくつかのノードを削除する必要があります。xmlから子を削除して送料を返す

これは私のコードです:

<Deal> 
    <SelectedDeal>+1</SelectedDeal> 
</Deal> 
<Property> 
    <PropertyId>8215</PropertyId> 
    <HPIValueChanged>1</HPIValueChanged> 
</Property> 
<FundBooking> 
    <ProductCode>J128R?</ProductCode> 
    <ControlNumber>   </ControlNumber> 
    </FundBooking> 

そして、これは実行するときに、私が得たものである:

String xmlProduct = ""; //my xml above 
    if(!xmlProduct.equals("")){ 
     InputSource is = new InputSource(); 
     is.setCharacterStream(new StringReader(xmlProduct)); 
     Document dom; 
     DocumentBuilderFactory dbf = (DocumentBuilderFactory) DocumentBuilderFactory.newInstance(); 
     DocumentBuilder db = (DocumentBuilder) dbf.newDocumentBuilder(); 
     dom = db.parse(is); 
     dom.normalize(); 


    //delete property 


    NodeList nodoProperty = dom.getDocumentElement().getElementsByTagName("Property"); 

    for(int i=0; i<nodoProperty.getLength(); i++){ 
     Node nodoBorrar = nodoProperty.item(i); 
     nodoRaizXML.item(0).removeChild(nodoBorrar); 

    } 
} 

//Convert to xml format 

    TransformerFactory tf = TransformerFactory.newInstance(); 
    Transformer transformer = tf.newTransformer(); 
    StringWriter writer = new StringWriter(); 
    transformer.transform(new DOMSource(dom), new StreamResult(writer)); 

これは私のxmlの一例である

<Deal> 
    <SelectedDeal>+1</SelectedDeal> 
</Deal> 


<FundBooking> 
    <ProductCode>J128R?</ProductCode> 
    <ControlNumber>   </ControlNumber> 
</FundBooking> 

タグであります削除されましたが、ファイル内のスペースを削除する必要があります。

はどのようにして行うことができます。この

+1

そして、どのようにあなたが戻ってファイルへハァッあなたのXMLを書いています? – Antoniossss

+0

私のコードを変換 – cucuru

答えて

1

これは、迅速な&汚れソリューションです:

xmlProduct = xmlProduct.replaceAll("\n", "").replaceAll("\r", ""); 
//... 
Transformer transformer = tf.newTransformer(); 
transformer.setOutputProperty(OutputKeys.INDENT, "yes"); 
+0

で更新しました申し訳ありませんが、私は親切に失われています、どの変数がxmlPropertyであるのかわかりません – cucuru

+0

@cucuru申し訳ありませんが、私は答えを修正しました。基本的には、解析する前にすべてのキャリッジリターンと改行をXMLストリングから置き換えてから、トランスフォーマーに出力をインデントするように指示します。 –

+0

ありがとう!それは動作しません、私は何が起こっているのか理解できません! – cucuru

関連する問題