2015-05-23 12 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

Смежные вопросы