2015-05-23 118 views
1

我想一個新的節點添加到XML根到下面的XML文件新節點添加到XML文件

<?xml version="1.0" encoding="utf-8"?> 
<Transactions> 
    <Transaction> 
    <Id>CUST9</Id> 
    <SMSFileName>Customer9.txt</SMSFileName> 
    <Mobile>918886002141</Mobile> 
    </Transaction> 
</Transactions> 

應該落得像

<?xml version="1.0" encoding="utf-8"?> 
<Transactions> 
    <Transaction> 
    <Id>CUST9</Id> 
    <SMSFileName>Customer9.txt</SMSFileName> 
    <Mobile>918886002141</Mobile> 
    </Transaction> 
    <Transaction> 
    <Id>CUST1</Id> 
    <SMSFileName>Customer1.txt</SMSFileName> 
    <Mobile>918886002141</Mobile> 
    </Transaction> 

</Transactions> 

我曾嘗試以下代碼,但還沒有工作

private void RemoveSuccessFullElements(string xmlFile, string transactionNumber) 
    { 
     FileInfo xmlFileInfo = new FileInfo(xmlFile); 
     var rootDirectoryForCurrentFolder = xmlFileInfo.Directory.FullName; 
     XmlDocument xDocument = new XmlDocument(); 
     xDocument.Load(xmlFile); 
     var archivedXmlFile = Directory.GetFiles(rootDirectoryForCurrentFolder).ToList().Where(t => t.ToLower().Contains("archived") && t.ToLower().Contains("xml")).FirstOrDefault(); 
     if (archivedXmlFile != null) 
     { 
      FileInfo archivedFileInfo = new FileInfo(archivedXmlFile); 

      XmlDocument xDocumentArchived = new XmlDocument(); 
      xDocumentArchived.Load(archivedXmlFile); 
      foreach (XmlNode node in xDocument.SelectNodes("Transactions/Transaction")) 
      { 
       var transactionIDExistanceResult = isTransactionIdExists(node); 
       if (transactionIDExistanceResult) 
       { 
        if (node.SelectSingleNode("Id").InnerText == transactionNumber) 
        { 

         node.ParentNode.RemoveChild(node); 

        **I want to add this removed node to new archivedXmlFile file** 

        } 
       } 

      } 
      xDocument.Save(xmlFile); 
     } 

    } 

任何線索

回答

2

然後你需要ImportNode和AppendChild:xDocumentArchived.DocumentElement.AppendChild(xDocumentArchived.ImportNode(node, true);。最後,您需要撥打xDocumentArchived上的保存號碼:xDocumentArchived.Save(archivedXmlFile);

+0

謝謝,我會試試看,讓你知道 – Vivekh