我有一个像这样的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>
我正在尝试过滤那些具有类型属性值为“编辑”的交互元素,并将它们写入新的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但它也没有用,有什么帮助吗?
答案 0 :(得分:1)
您无法从一个文档中获取节点并将其放入另一个文档中。您必须使用现有节点中的数据为目标文档创建新节点。
答案 1 :(得分:0)
您应该将nNode
导入docnew
第一个
修改您的代码如下:
if(value.equalsIgnoreCase("edit"))
{
Node imported_node = docnew.importNode(nNode, true);
Element eElement = (Element) imported_node;
rootElement.insertBefore(eElement,null);
}
干杯!