次のような 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」の Interaction 要素をフィルタリングし、次のように新しい 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 を試しましたが、うまくいきませんでした。