简体   繁体   中英

Append XML node C#

I have 2 xml files that need to be combined.

Test1.xml is below

<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 is below

<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>

This is the expected output.

<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>

We are trying to take "Chapter" node from Test2.xml and append it to Test1.xml. This is part of C# program I wrote.

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);

I am not sure why myNode is null. I am not quite sure how to append the nodes. Any help is appreciated.

Thanks MR

I am not sure why myNode is null

You forgot to use the XmlNamespace 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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM