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

让人想犯罪 __ 提交于 2020-01-13 19:26:27

问题


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!


回答1:


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.



来源:https://stackoverflow.com/questions/90803/convert-c-sharp-2-0-system-data-sqltypes-sqlxml-object-into-a-system-xml-xmlnode

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!