我有一个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>
标记已删除,但我需要删除其在文件中的空间。
我该怎么做
1条答案
按热度按时间46scxncf1#
这是快速和肮脏的解决方案: