我有一个这样的 XML 文件:
<Interactions>
<Interaction Delta="null" Kind="propagation" StructureKind="resource"/>
<Interaction Delta="null" Kind="edit" StructureKind="resource"/>
<Interaction Delta="null" Kind="select" StructureKind="resource"/>
<Interaction Delta="null" Kind="edit" StructureKind="resource"/>
</Interactions>
我正在尝试过滤那些具有 kind 属性值为“edit”的交互元素,并将它们写入新的 XML 文件中,如下所示:
<bug>
<Interaction Delta="null" Kind="edit" StructureKind="resource"/>
<Interaction Delta="null" Kind="edit" StructureKind="resource"/>
</bug>
这是我的代码:
public class xslt{
public static String dirPath = "/home/";
public static void main(String[] args) {
try{
File fXmlFile= new File(dirPath+"file.xml");
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(fXmlFile);
doc.getDocumentElement().normalize();
NodeList nList = doc.getElementsByTagName("Interaction");
DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
Document docnew = docBuilder.newDocument();
Element rootElement = docnew.createElement("bugid");
docnew.appendChild(rootElement);
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
StreamResult result = new StreamResult(new File(dirPath+"result2.xml"));
for (int temp=0; temp<nList.getLength();temp++) {
Node nNode = nList.item(temp);
String value;
value=nNode.getAttributes().getNamedItem("Kind").getNodeValue();
if(value.equalsIgnoreCase("edit"))
{
Element eElement = (Element) nNode;
rootElement.insertBefore(eElement,null);
}
}
DOMSource source = new DOMSource(docnew);
transformer.transform(source, result);
}
catch(Exception e)
{e.printStackTrace();}
}
}
但我的程序有错误:一个节点在与创建它的文档不同的文档中使用。问题与这一行有关:rootElement.insertBefore(eElement,null); 我尝试了 appendelement 但它也不起作用,有什么帮助吗?