views:

373

answers:

2

I have an XmlDocument that is from a webservice, and I want to use a subset of the xml to populate a Gridview control. Unfortunately, it contains extra data that I don't need. So I want to create a new XmlDocument from a subset of the existing xml document.

protected void Page_Load(object sender, EventArgs e)
{
   XmlDocument xmlDoc = Object.ReturnsXmlDocument;
   XmlDocument xmlDocResults = ???  //<results><result></result></results>
}

Basically, I want to create a new XmlDocument with the as the root element. Below is a shortened example of the original xml doc:

<?xml version="1.0" encoding="UTF-8"?>
<xml>
   <query_time>.12</query_time>
   <number_results>3</number_results>
   <results>
     <result><id>1</id></result>
     <result><id>2</id></result>
     <result><id>3</id> </result>
   </results>
</xml>

Anthony's code helped point me in the right direction, but this is what actually worked for me.

XmlDocument xmlResults = new XmlDocument();
    XmlDeclaration xmlDec = xmlResults.CreateXmlDeclaration("1.0", "utf-8", null);
    XmlElement rootNode = xmlResults.CreateElement("results");
    xmlResults.InsertBefore(xmlDec, xmlResults.DocumentElement);
    xmlResults.AppendChild(rootNode);

    XmlNode node = xmlDoc.GetElementsByTagName("results")[0];

    xmlResults.GetElementsByTagName("results")[0].InnerXml = node.InnerXml.ToString();
+2  A: 

What you need is ImportNode:-

XmlDocument xmlDoc = Object.ReturnsXmlDocument;
XmlDocument xmlResults = new XmlDocument();
xmlResults.AppendNode(xmlResults.ImportNode(xmlDoc.SelectSingleNode("/xml/results"));
AnthonyWJones
+1  A: 

Untested, but this should be pretty darn close:

XPathDocument original = new XPathDocument("original.xml");
XPathNavigator navigator = original.CreateNavigator();
navigator.MoveToChild("results", "");
XmlWriter results = XmlWriter.Create("results.xml");
navigator.WriteSubtree(results);
results.Close();

And then you can do whatever you need to with the XmlWriter - I'm not sure if you're trying to create the results XmlDocument on disk or not.

Matt Ball