繁体   English   中英

从xml中删除子项并回车

[英]delete child and return carriage from xml

我有一个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>

标签被删除,但我需要删除它在文件中的空间。

我怎样才能做到这一点

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM