Get XML content from XmlNodeList

1.6k views Asked by At

I have a question that may seem very simple, but it's giving me a headache. I have this XML file that has multiple entries, like:

    <books>
     <book>
      <id>1</id>
      <firstCover>
       <author name="**" age="**" />
       <title name="zz" font="yyy" size="uuu"/>
      </firstCover>
      <lastCover>
      </lastCover>
     </book>
     <book>
      <id>2</id>
      <firstCover>
       <author name="**" age="**" />
       <title name="zz" font="yyy" size="uuu"/>
      </firstCover>
      <lastCover>
      </lastCover>
     </book>
</books>

Now, in order to get the XML content for first cover of book with id=1, I do this:

XmlNodeList b = root.SelectNodes("/books/book[contains(id,1)]/firstCover");

Then I would really need to take the whole content of what's inside the firstCover for that book :

<author name="**" age="**" />
<title name="zz" font="yyy" size="uuu"/>

and insert it into an XmlElement. This is where I'm stucked. I know I can do it with a foreach loop in XmlNodeList, but is there a more simple way?

1

There are 1 answers

0
Paul Farry On

I'm guessing you want to actually insert it into an XMLElement in another XMLDocument.

Is this what you are looking for?

XmlDocument sourceDoc = new XmlDocument();
//This is loading the XML you present in your Question.
sourceDoc.LoadXml(xmlcopier.Properties.Resources.data);
XmlElement root = sourceDoc.DocumentElement;


XmlElement b = (XmlElement)root.SelectSingleNode("/books/book[contains(id,1)]/firstCover");

XmlDocument destDoc = new XmlDocument();
XmlElement destRoot = destDoc.CreateElement("base");
destDoc.AppendChild(destRoot);
XmlElement result = destDoc.CreateElement("firstCover");


result.InnerXml = b.InnerXml;
destRoot.AppendChild(result);


destDoc.Save("c:\\test.xml");