3

我有一个这样的 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 但它也不起作用,有什么帮助吗?

4

2 回答 2

3

你应该先导入你nNodedocnew

修改您的代码如下:

if(value.equalsIgnoreCase("edit"))
{   
    Node imported_node = docnew.importNode(nNode, true);
    Element eElement = (Element) imported_node;
    rootElement.insertBefore(eElement,null);
}

干杯!

于 2013-11-20T07:39:42.170 回答
2

You can't get a node from one document and put it into another document. You have to create a new node for the target document using the data from the existing node.

于 2013-11-15T02:14:00.593 回答