从xml中删除子代并返回回车符

hs1ihplo  于 2021-07-13  发布在  Java
关注(0)|答案(1)|浏览(382)

我有一个xml文件,有时我不得不删除一些节点。
这是我的密码:

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>
<Property>
   <PropertyId>8215</PropertyId>
   <HPIValueChanged>1</HPIValueChanged>
 </Property>
 <FundBooking>
    <ProductCode>J128R?</ProductCode>
     <ControlNumber>            </ControlNumber>
  </FundBooking>

这是我执行时得到的:

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

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

标记已删除,但我需要删除其在文件中的空间。
我该怎么做

46scxncf

46scxncf1#

这是快速和肮脏的解决方案:

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

相关问题