2017-08-15 72 views
0

我有2個需要合併的xml文件。追加XML節點C#

Test1.xml低於

<ProfileSearchResponse xmlns="xxxRestServices" xmlns:i="http://www.w3.org/2001/XMLSchema-instance"> 
    <Profile> 
    <Category> 
     <a>Test1 string</a> 
     <b>Test3 string</b> 
    </Category> 
    <Chapters> 
     <Chapter> 
      <Name>bi weekly Update</Name> 
     </Chapter> 
    </Chapters> 
     <Disclaimer>"The purpose of the Profiles is xxxxxx </Disclaimer> 
     <RelatedProfiles>Blah blah testing this </RelatedProfiles> 
</Profile> 
</ProfileSearchResponse> 

Test2.xml低於

<ProfileSearchResponse xmlns="xxxRestServices" xmlns:i="http://www.w3.org/2001/XMLSchema-instance"> 
    <Profile> 
     <Chapters> 
      <Chapter> 
       <Name>Previous bi weekly Updates</Name> 
      </Chapter> 
     </Chapters> 
     <Disclaimer>"The purpose of the Profiles is xxxxxx </Disclaimer> 
    </Profile> 
</ProfileSearchResponse> 

這是預期的輸出。

<ProfileSearchResponse xmlns="xxxRestServices" xmlns:i="http://www.w3.org/2001/XMLSchema-instance"> 
    <Profile> 
    <Category"> 
     <a>Test1 string</a> 
     <b>Test3 string</b> 
    </Category> 
    <Chapters> 
     <Chapter> 
      <Name>bi weekly Update</Name> 
     </Chapter> 
     <Chapter> 
      <Name>Previous bi weekly Updates</Name> 
     </Chapter> 
    </Chapters> 
     <Disclaimer>"The purpose of the Profiles is xxxxxx </Disclaimer> 
     <RelatedProfiles>Blah blah testing this </RelatedProfiles> 
</Profile> 
</ProfileSearchResponse> 

我們試圖從Test2.xml中取出「Chapter」節點並將其附加到Test1.xml中。 這是我編寫的C#程序的一部分。

XmlDocument document1 = new XmlDocument(); 
      XmlDocument document2 = new XmlDocument(); 
      document1.Load(@"C:\test1.xml"); 
      document2.Load(@"C:\test2.xml"); 
      XmlNode myNode = document2.DocumentElement.SelectSingleNode("//Chapter"); 
     document1.DocumentElement.AppendChild(myNode); 

我不知道爲什麼myNode爲null。我不太清楚如何附加節點。任何幫助表示讚賞。

感謝 MR

+0

文檔1,你需要得到的章節,並添加一個新的章節到現有的標籤章節。 – jdweng

回答

0

我不知道爲什麼MYNODE是空

你忘了使用XML命名空間xxxRestServices

XmlDocument document2 = new XmlDocument(); 
document2.Load(@"d:\temp\a.txt"); 

XmlNamespaceManager mgr = new XmlNamespaceManager(document2.NameTable); 
mgr.AddNamespace("ns", "xxxRestServices"); 

XmlNode myNode = document2.DocumentElement.SelectSingleNode("//ns:Chapter",mgr); 
+0

在我的代碼之後,我添加了document1.DocumentElement.AppendChild(myNode);我得到「要插入的節點來自不同的文檔上下文。」這是什麼意思 – user2726975

+0

'這是什麼意思?'把錯誤信息寫入谷歌並打開第一個鏈接。 'var newNode = document1.ImportNode(myNode,true); document1.DocumentElement.AppendChild(newNode);' –