简体   繁体   中英

Convert C# 2.0 System.Data.SqlTypes.SqlXml object into a System.Xml.XmlNode

I seem to always have problems with converting data to and from XML in C#. It always wants you to create a full XMLDocument object even when you think you shouldn't have to. In this case I have a SQLXML column in a MS SQL 2005 server that I am trying to pull out and push into a function that requires an XMLNode as a parameter. You would think this would be easy, but outside of converting it to a string and creating a new XMLNode object I cannot figure out the right way to do it.

I can use an SqlDataReader, the sqlComm.ExecuteReader() to load the reader, and sqlReader.GetSqlXml(0) to get the SQLXML object,but then how do I convert it to an XmlNode?

Conversely I can use the sqlComm.ExecuteXmlReader() to get an XmlReader, but how do I extract a XmlNode from the reader? http://bytes.com/forum/thread177004.html says it cannot be done with a XmlTextReader, should I use a XmlNodeReader?

Help please!

I ended up not having to use it, but I found what I think is the best answer. Basically you load an XmlReader, create an XmlDocument from the reader, then select a list of nodes from the document into an XmnLodeList, which you can use in a ForEach statement. Here is some sample code:

System.Xml.XmlReader sqlXMLReader = sqlComm.ExecuteXmlReader();
System.Xml.XmlDocument xmlDoc = new System.Xml.XmlDocument();
xmlDoc.Load(sqlXMLReader);
System.Xml.XmlNodeList xnlJobs = xmlDoc.SelectNodes("/job");

Still convoluted as hell, but at least there are no xml to string to xml conversions.

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