2016-05-18 22 views
0

我有一個XML文件,我需要刪除特定的節點。要刪除的節點將根據邏輯動態定義。我一直在網上尋找解決方案,但仍然無法刪除我的節點。出現錯誤 - NOT_FOUND_ERR: An attempt is made to reference a node in a context where it does not exist無法刪除XML中的特定節點

下面是一個示例XML文件。我需要刪除節點<NameValuePairs>其中有<name>Local Variables</name>。下面是我的示例XML文件中的Java代碼

示例XML文件

<?xml version="1.0" encoding="UTF-8"?> 
<DeploymentDescriptors xmlns="http://www.tibco.com/xmlns/dd"> 
<name>Test</name> 
<version>1</version> 
<DeploymentDescriptorFactory> 
    <name>RepoInstance</name> 
</DeploymentDescriptorFactory> 
<DeploymentDescriptorFactory> 
    <name>NameValuePairs</name> 
</DeploymentDescriptorFactory> 
<NameValuePairs> 
    <name>Global Variables</name> 
    <NameValuePair> 
     <name>Connections1</name> 
     <value>7222</value> 
     <requiresConfiguration>true</requiresConfiguration> 
    </NameValuePair> 
    <NameValuePair> 
     <name>Connections2</name> 
     <value>7222</value> 
     <requiresConfiguration>true</requiresConfiguration> 
    </NameValuePair> 
</NameValuePairs> 
<NameValuePairs> 
    <name>Local Variables</name> 
    <NameValuePair> 
     <name>Connections3</name> 
     <value>8222</value> 
     <requiresConfiguration>true</requiresConfiguration> 
    </NameValuePair> 
    <NameValuePair> 
     <name>Connections3</name> 
     <value>8222</value> 
     <requiresConfiguration>true</requiresConfiguration> 
    </NameValuePair> 
</NameValuePairs> 
</DeploymentDescriptors> 

Java代碼的

File fDestFile = new File("myfile.xml"); 
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); 
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder(); 
Document oDoc3 = dBuilder.parse(fDestFile); 
NodeList oDestFlowList = oDoc3.getElementsByTagName("NameValuePairs"); 
for (int m = 0; m < oDestFlowList.getLength(); m++) { 
    NodeList oDestchildList = oDestFlowList.item(m).getChildNodes(); 
    for (int n = 0; n < oDestchildList.getLength(); n++) { 
      Node oDestchildNode = oDestchildList.item(n); 
      if ("name".equals(oDestchildNode.getNodeName())) { 
      //oDestchildNode.getParentNode().removeChild(oDestchildNode); //Not Working 
      //oDoc3.getDocumentElement().removeChild(oDestchildNode); //Not Working 
      } 
     } 
    } 
} 
+0

哪個代碼行生成錯誤的代碼的最後一塊? – jtahlborn

+0

我沒有收到任何錯誤。我試圖刪除的子元素沒有被上面的代碼刪除。 – Lettisha

回答

1

下面是終於研究出

public static void main(String[] args) { 
    File fXmlSubFile = new File("Sub.xml"); 
    File fXmlOriginalFile = new File("Original.xml"); 
    File fDestFile = new File("myfile.xml"); 
    DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); 
    DocumentBuilder dBuilder; 
    FileChannel source = null; 
    FileChannel destination = null; 
    XPath xPath = XPathFactory.newInstance().newXPath(); 

    try{ 
     if (!fDestFile.exists()) { 
      fDestFile.createNewFile(); 
     } 
     source = new FileInputStream(fXmlOriginalFile).getChannel(); 
     destination = new FileOutputStream(fDestFile).getChannel(); 
     if (destination != null && source != null) { 
      destination.transferFrom(source, 0, source.size()); 
     } 
     if (source != null) { 
      source.close(); 
     } 
     if (destination != null) { 
      destination.close(); 
     } 
     dBuilder = dbFactory.newDocumentBuilder(); 
     Document oSubDoc = dBuilder.parse(fXmlSubFile); 
     Document oDestDoc = dBuilder.parse(fDestFile); 
     oSubDoc.getDocumentElement().normalize(); 
     oDestDoc.getDocumentElement().normalize(); 

     String sDestExpression = "/DeploymentDescriptors/NameValuePairs"; 
     String sSubExpression = "/NameValuePairs"; 
     NodeList nodeDestList = (NodeList) xPath.compile(sDestExpression).evaluate(oDestDoc, XPathConstants.NODESET); 
     NodeList nodeSubList = (NodeList) xPath.compile(sSubExpression).evaluate(oSubDoc, XPathConstants.NODESET); 
     for (int i = nodeDestList.getLength()-1; i >=0 ; i--) { 
      Node oDestNode = nodeDestList.item(i); 
      if (oDestNode.getNodeType() == Node.ELEMENT_NODE) { 
       Element oDestElement = (Element) oDestNode; 
       for (int j =0; j<nodeSubList.getLength(); j++) { 
        Node oSubNode = nodeSubList.item(j); 
        if (oSubNode.getNodeType() == Node.ELEMENT_NODE) { 
         Element oSubElement = (Element) oSubNode; 
         if(oDestElement.getElementsByTagName("name").item(0).getTextContent().equals(oSubElement.getElementsByTagName("name").item(0).getTextContent())){ 
         oDestNode.getParentNode().removeChild(oDestNode); 
         } 
        } 
       } 
      } 
     } 
     Source src = new DOMSource(oDestDoc); 
     Result result = new StreamResult(fDestFile); 
     Transformer transformer = null; 
     transformer = TransformerFactory.newInstance().newTransformer(); 
     // Transform your XML document (i.e. save changes to file) 
     transformer.transform(src, result); 
    }catch(Exception ex){ 
     System.out.println("error:"+ex.getMessage()); 
     ex.printStackTrace(); 
    } 
} 
1

你需要創建一個從父節點的單獨引用作爲元素,讓你不參考您正在刪除的節點:

File fDestFile = new File("src/myfile.xml"); 
    DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); 
    DocumentBuilder dBuilder = null; 
    try { 
     dBuilder = dbFactory.newDocumentBuilder(); 
     Document oDoc3 = null; 
     oDoc3 = dBuilder.parse(fDestFile); 
     NodeList oDestFlowList = oDoc3.getElementsByTagName("NameValuePairs"); 
     // Loop through all 'NameValuePairs' 
     for (int m = oDestFlowList.getLength()-1; m >=0 ; m--) { 
      NodeList oDestchildList = oDestFlowList.item(m).getChildNodes(); 
      // Loop through children of 'NameValuePairs' 
      for (int n = oDestchildList.getLength()-1; n >=0 ; n--) { 
       // Remove children if they are of the type 'name' 
       if(oDestchildList.item(n).getNodeName().equals("name")){ 
        oDestFlowList.item(m).removeChild(oDestchildList.item(n)); 
        // For debugging 
        System.out.println(oDestchildList.item(n).getNodeName()); 
       } 
      } 
     } 
     Source source = new DOMSource(oDoc3); 
     Result result = new StreamResult(fDestFile); 
     Transformer transformer = null; 
     transformer = TransformerFactory.newInstance().newTransformer(); 
     // Transform your XML document (i.e. save changes to file) 
     transformer.transform(source, result); 
    } catch (Exception e) { 
     // Catch the exception here 
     e.printStackTrace(); 
    } 
} 

如果您仍然有問題,那麼我wo我認爲這是節點類型的問題。在我爲'oDestchildNode.getNodeType()'進行檢查之前,這是爲我工作的,但是我會查看您返回並從那裏返回的節點類型。

+0

感謝您的快速響應。我已經嘗試了您的解決方案,但我們無法將節點分配給元素。我收到鑄造錯誤行元素節點=(元素)oDestchildList.item(i); – Lettisha

+0

嘗試以下2個選項後,我收到投射錯誤 選項1: 元素節點=(元素)oDestchildList.item(i); Element elemenet = node.getParentNode();選項2: 節點oDestchildNode = oDestchildList.item(n); Element elemenet = oDestchildNode.getParentNode(); 有人可以幫我解決這個問題 – Lettisha

+0

你使用'org.w3c.dom.Element'類嗎? – ghg565