我是 xml 解析的新手,我们是否可以更新或修改,例如在运行时使用 SAX 解析器删除 XML 的节点,并将更新的数据作为 XML 流式传输,或者如果我们需要将其转换为我们自己的格式?正如 DOM 解析器所做的那样。
dbFactory = DocumentBuilderFactory.newInstance();
docBuilder = dbFactory.newDocumentBuilder();
document = docBuilder.parse("src/"+xmlFile);
tranformerFactory = TransformerFactory.newInstance();
transformer = tranformerFactory.newTransformer();
for (int i = 0; i < inputElementsArrayToRemove.length; i++)
{
element = (Element)document.getElementsByTagName(inputElementsArrayToRemove[i]).item(0);
if(element != null)
{
// Removes the node from the document
element.getParentNode().removeChild(element);
}
}
// Normalize the DOM tree to combine all adjacent nodes
document.normalize();
// Here, transforming(Converting) the document source to the another XML file
Source source = new DOMSource(document);
Result dest = new StreamResult(new FileOutputStream(new File("src/"+resultXmlFileName)));
// transform method to write out the DOM as XML data.
transformer.transform(source, dest);