Thursday, March 27, 2008

XmlReader Objects With No Root Element and Converting them to XmlDocument Objects

I had this problem this week where I had an XmlReader object coming back from an SQL stored procedure using "FOR XML AUTO, ELEMENTS" but that XML returned was a record set and could not be converted into a XmlDocument using the '.Load(XmlReader reader)' method because of the missing root element.


  SqlCommand cmd = new SqlCommand();

  cmd.CommandText = sQuery;

  cmd.Connection = oConn;

  cmd.CommandType = CommandType.Text;

  XmlReader xmlRead = cmd.ExecuteXmlReader();

 

  XPathDocument xp = new XPathDocument(xmlRead);

  XPathNavigator xn = xp.CreateNavigator();

  XmlDocument xd = new XmlDocument();

  XmlNode root = xd.CreateElement(sRootName);

  root.InnerXml = xn.OuterXml;

  xd.AppendChild(root);

  oConn.Close();

  return xd;


Or you could just use, as I found out later, FOR XML AUTO, ELEMENTS, ROOT('ElementName') which works even better and then no messing around with C#.

No comments: