473,804 Members | 2,195 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

SQL 'for xml' and C# example??

I'm missing some piece of the puzzle. I'm using 'for xml' type queries from
SQL2K - and now trying to change the front-end from ADO to C#, I can't quite
figure it out..

It seems that I could use an XmlReader.. and somehow use that instead of a
DataReader.. but that didn't work.. I tried using a DataReader and get the
byte array - but that wasn't right.

SQL returns formatted XML, I need to load that XML into an XmlDocument
somehow without ANY molestation of that dom. Any ideas? Examples? Missing
links????

thanks
Nov 11 '05 #1
4 22714
THANKS!! I've been looking for the answer to these for weeks. I always do
things with System.Data.Ole Db.* - and this actually dawned on my a little
while ago - so I stumbled across the same answer.

I have one followup, with this code:

XmlReader xmlReader = objCmd.ExecuteX mlReader();
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(xml Reader);
xmlReader.Close ();
string strText = xmlDoc.OuterXml ;

And xmlDoc.OuterXml at a breakpoint at the last line, is
"<CLIENTINFO><C LIENTID>1234123 41234</CLIENTID> (bunch of elements
deleted)</CLIENTINFO>" - which is correct and valid.

But if I try to read OuterXml or InnerText into a variable (like the last
line of code), I get and exception of "This document already has a
DocumentElement node."

Any ideas? This same stored procedure works with legacy ADO... Thanks
again!!
"SQL Server Development Team [MSFT]" <sq****@microso ft.com> wrote in message
news:Ow******** ******@tk2msftn gp13.phx.gbl...
The SqlCommand class has an ExecuteXmlReade r method.
See
http://msdn.microsoft.com/library/de...eaderTopic.asp
Here's the cut a pasted example

[C#]
public void CreateMyXmlRead er(string myXmlQuery, SqlConnection myConnection) {
// For the myXmlQuery append the "for XML" statement to the end of the SQL
Query
SqlCommand myCommand = new SqlCommand(myXm lQuery, myConnection);
try
{
myConnection.Op en();

System.Xml.XmlR eader myXmlReader = myCommand.Execu teXmlReader();

// Always close the XmlReader when finished.
myXmlReader.Clo se();
}
catch(Exception e)
{
System.Diagnost ics.EventLog log = new System.Diagnost ics.EventLog();
log.Source = "My Application";
log.WriteEntry( e.ToString());
Console.WriteLi ne("Exception of type {0} occurred.", e.GetType());
}
finally
{
myConnection.Cl ose();
}
}

Mark Fussell
PM - System.Xml

--
This posting is provided "AS IS" with no warranties, and confers no rights. Use of included script samples are subject to the terms specified at
http://www.microsoft.com/info/cpyright.htm.
"Drebin" <tR************ *@hotmail.com> wrote in message
news:iS******** *********@newss vr31.news.prodi gy.com...
I'm missing some piece of the puzzle. I'm using 'for xml' type queries

from
SQL2K - and now trying to change the front-end from ADO to C#, I can't

quite
figure it out..

It seems that I could use an XmlReader.. and somehow use that instead of a DataReader.. but that didn't work.. I tried using a DataReader and get the byte array - but that wasn't right.

SQL returns formatted XML, I need to load that XML into an XmlDocument
somehow without ANY molestation of that dom. Any ideas? Examples? Missing links????

thanks


Nov 11 '05 #2
Ummm. I am surprised that it let you load the returned XML. By default the
For XML query returns XML fragments with no "wrapping" document element
node. This will fail when loaded into the XmlDocument class. Usually you
have one of three choices;

1) Create an document element node before setting the InnerXml property on
the XmlDocument from the XmlReader's InnerXml.
2) Create a document element node for the FOR XML query using the &root
append. See http://www.sqlxml.org/faqs.aspx?faq=16
3) Use the XPathDocument class that can load XML fragements if you do not
want a document element node i.e You want an XML fragment. The only issue
here is that you have to save this out via an XPathNavigator which takes
more code.

I would look though examples that Dan has from his book.
http://www.xmlforasp.net/codeSection.aspx?csID=1
See CH8 approx - SQL Server and XML.

Thanks. Mark
PM - System.Xml
--
This posting is provided "AS IS" with no warranties, and confers no rights.
Use of included script samples are subject to the terms specified at
http://www.microsoft.com/info/cpyright.htm.
"Drebin" <tR************ *@hotmail.com> wrote in message
news:HT******** *********@newss vr31.news.prodi gy.com...
THANKS!! I've been looking for the answer to these for weeks. I always do
things with System.Data.Ole Db.* - and this actually dawned on my a little
while ago - so I stumbled across the same answer.

I have one followup, with this code:

XmlReader xmlReader = objCmd.ExecuteX mlReader();
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(xml Reader);
xmlReader.Close ();
string strText = xmlDoc.OuterXml ;

And xmlDoc.OuterXml at a breakpoint at the last line, is
"<CLIENTINFO><C LIENTID>1234123 41234</CLIENTID> (bunch of elements
deleted)</CLIENTINFO>" - which is correct and valid.

But if I try to read OuterXml or InnerText into a variable (like the last
line of code), I get and exception of "This document already has a
DocumentElement node."

Any ideas? This same stored procedure works with legacy ADO... Thanks
again!!
"SQL Server Development Team [MSFT]" <sq****@microso ft.com> wrote in message news:Ow******** ******@tk2msftn gp13.phx.gbl...
The SqlCommand class has an ExecuteXmlReade r method.
See

http://msdn.microsoft.com/library/de...eaderTopic.asp

Here's the cut a pasted example

[C#]
public void CreateMyXmlRead er(string myXmlQuery, SqlConnection

myConnection)
{
// For the myXmlQuery append the "for XML" statement to the end of the SQL
Query
SqlCommand myCommand = new SqlCommand(myXm lQuery, myConnection);
try
{
myConnection.Op en();

System.Xml.XmlR eader myXmlReader = myCommand.Execu teXmlReader();

// Always close the XmlReader when finished.
myXmlReader.Clo se();
}
catch(Exception e)
{
System.Diagnost ics.EventLog log = new System.Diagnost ics.EventLog(); log.Source = "My Application";
log.WriteEntry( e.ToString());
Console.WriteLi ne("Exception of type {0} occurred.", e.GetType());
}
finally
{
myConnection.Cl ose();
}
}

Mark Fussell
PM - System.Xml

--
This posting is provided "AS IS" with no warranties, and confers no

rights.
Use of included script samples are subject to the terms specified at
http://www.microsoft.com/info/cpyright.htm.
"Drebin" <tR************ *@hotmail.com> wrote in message
news:iS******** *********@newss vr31.news.prodi gy.com...
I'm missing some piece of the puzzle. I'm using 'for xml' type queries

from
SQL2K - and now trying to change the front-end from ADO to C#, I can't

quite
figure it out..

It seems that I could use an XmlReader.. and somehow use that instead

of a DataReader.. but that didn't work.. I tried using a DataReader and get the byte array - but that wasn't right.

SQL returns formatted XML, I need to load that XML into an XmlDocument
somehow without ANY molestation of that dom. Any ideas? Examples? Missing links????

thanks



Nov 11 '05 #3
Actually - my problem is just the opposite, the query DOES wrap everything
in a root element... And we already have a bunch of complex stored
procedures that already work this way...

It's almost like XmlDocument is trying to put a wrapper tag and there is
already one. Any other ideas?? And thanks VERY much for your help - even if
I don't get this working - you've already advanced me quite a bit, because I
was at a dead end!!
"SQL Server Development Team [MSFT]" <sq****@microso ft.com> wrote in message
news:Ox******** ******@TK2MSFTN GP11.phx.gbl...
Ummm. I am surprised that it let you load the returned XML. By default the
For XML query returns XML fragments with no "wrapping" document element
node. This will fail when loaded into the XmlDocument class. Usually you
have one of three choices;

1) Create an document element node before setting the InnerXml property on
the XmlDocument from the XmlReader's InnerXml.
2) Create a document element node for the FOR XML query using the &root
append. See http://www.sqlxml.org/faqs.aspx?faq=16
3) Use the XPathDocument class that can load XML fragements if you do not
want a document element node i.e You want an XML fragment. The only issue
here is that you have to save this out via an XPathNavigator which takes
more code.

I would look though examples that Dan has from his book.
http://www.xmlforasp.net/codeSection.aspx?csID=1
See CH8 approx - SQL Server and XML.

Thanks. Mark
PM - System.Xml
--
This posting is provided "AS IS" with no warranties, and confers no rights. Use of included script samples are subject to the terms specified at
http://www.microsoft.com/info/cpyright.htm.
"Drebin" <tR************ *@hotmail.com> wrote in message
news:HT******** *********@newss vr31.news.prodi gy.com...
THANKS!! I've been looking for the answer to these for weeks. I always do
things with System.Data.Ole Db.* - and this actually dawned on my a little while ago - so I stumbled across the same answer.

I have one followup, with this code:

XmlReader xmlReader = objCmd.ExecuteX mlReader();
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(xml Reader);
xmlReader.Close ();
string strText = xmlDoc.OuterXml ;

And xmlDoc.OuterXml at a breakpoint at the last line, is
"<CLIENTINFO><C LIENTID>1234123 41234</CLIENTID> (bunch of elements
deleted)</CLIENTINFO>" - which is correct and valid.

But if I try to read OuterXml or InnerText into a variable (like the last line of code), I get and exception of "This document already has a
DocumentElement node."

Any ideas? This same stored procedure works with legacy ADO... Thanks
again!!
"SQL Server Development Team [MSFT]" <sq****@microso ft.com> wrote in message
news:Ow******** ******@tk2msftn gp13.phx.gbl...
The SqlCommand class has an ExecuteXmlReade r method.
See

http://msdn.microsoft.com/library/de...eaderTopic.asp

Here's the cut a pasted example

[C#]
public void CreateMyXmlRead er(string myXmlQuery, SqlConnection

myConnection)
{
// For the myXmlQuery append the "for XML" statement to the end of the SQL Query
SqlCommand myCommand = new SqlCommand(myXm lQuery, myConnection);
try
{
myConnection.Op en();

System.Xml.XmlR eader myXmlReader = myCommand.Execu teXmlReader();

// Always close the XmlReader when finished.
myXmlReader.Clo se();
}
catch(Exception e)
{
System.Diagnost ics.EventLog log = new System.Diagnost ics.EventLog(); log.Source = "My Application";
log.WriteEntry( e.ToString());
Console.WriteLi ne("Exception of type {0} occurred.", e.GetType()); }
finally
{
myConnection.Cl ose();
}
}

Mark Fussell
PM - System.Xml

--
This posting is provided "AS IS" with no warranties, and confers no

rights.
Use of included script samples are subject to the terms specified at
http://www.microsoft.com/info/cpyright.htm.
"Drebin" <tR************ *@hotmail.com> wrote in message
news:iS******** *********@newss vr31.news.prodi gy.com...
> I'm missing some piece of the puzzle. I'm using 'for xml' type queries from
> SQL2K - and now trying to change the front-end from ADO to C#, I can't quite
> figure it out..
>
> It seems that I could use an XmlReader.. and somehow use that instead of
a
> DataReader.. but that didn't work.. I tried using a DataReader and
get the
> byte array - but that wasn't right.
>
> SQL returns formatted XML, I need to load that XML into an

XmlDocument > somehow without ANY molestation of that dom. Any ideas? Examples?

Missing
> links????
>
> thanks
>
>



Nov 11 '05 #4
>-----Original Message-----
I'm missing some piece of the puzzle. I'm using 'for xml' type queries fromSQL2K - and now trying to change the front-end from ADO to C#, I can't quitefigure it out..

It seems that I could use an XmlReader.. and somehow use that instead of aDataReader.. but that didn't work.. I tried using a DataReader and get thebyte array - but that wasn't right.

SQL returns formatted XML, I need to load that XML into an XmlDocumentsomehow without ANY molestation of that dom. Any ideas? Examples? Missinglinks????

thanks
.

Nov 11 '05 #5

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

8
3154
by: Wolfgang Lipp | last post by:
<annotation> the first eleven contributions in this thread started as an off-list email discussion; i have posted them here with the consent of their authors. -- _w.lipp </annotation> From: Eric van der Vlist Sent: Tuesday, 27?January?2004 13:53 Hi,
2
1993
by: jeffc | last post by:
I'm just learning XML and am reading "Inside XML" by Holzner. He gives an early XML example file. <?xml version = "1.0" encoding="UTF-8"?> <DOCUMENT> <GREETING> Hello From XML
8
2362
by: Sebastian Kerekes | last post by:
Greetings, I'm developing an application that supports multiple languages. In my XSL I use variables to place the text where it belongs to. At the top of the document I include those variables - the included file depends on the language. Atm I'm editing those file manually. Luckily atm it's only two languages I have to work with, but even in this case I forget to add a variable that I added in the other file, forget to use entities .....
3
1902
by: Henri Sivonen | last post by:
I am generating XML by emitting SAX events programmatically from Java. However, there's a lot of boilerplate markup, so being able to generate code from XML would be nice. Is there a tool that would take an XML file like this <?args org.xml.sax.ContentHandler ch, com.example.Foo foo ?> <baz xmlns="http://example.com/fooml/"> <?code foo.bar(ch); ?> </baz>
38
3619
by: Jukka K. Korpela | last post by:
As well all know, valid markup is important... but when trying to find a convincing modern argument in favor of this, I found pages like http://www.htmlhelp.com/tools/validator/reasons.html which was very nice when Netscape ruled the World Wide Web, and http://valet.htmlhelp.com/page/why.html which is very suggestive but does not really give any factual example. Is there something to be _shown_ to people who ask "why validate?"? A page...
3
1891
by: Patrick | last post by:
I have got 2 XML documents, both of which conform to the same XSD Schema, which define possible optional elements. The 2 XML documents contain 2 disjoint set of XML elements. What is the best, easiest, most efficient way of merging the 2 XML Documents? Can I use DataSet.Merge() facility in ADO.NET?? Any pre-requisites? Any other suggestions?
2
14602
by: Mark | last post by:
Hi there, I have two xml files, one is a master file and the other is just a fragment of xml. Master xml file uses 'DOCTYPE' to define the other file as an entity. Then, the master uses entity references that are supposed to be expanded into real content at parsing time. Examples are provided below. When I open master xml file in InternetExplorer , IE shows correct content. All the entities are transformed into right xml. So far I have...
11
2657
by: ajikoe | last post by:
Hello, I used Visual C# Standard Edition. I want to comment my program using xml commentary method, I don't know why if I use value and example tag, it is not working / showed in the html result. for example I have Property ///<value>this is in description</value> ///<example>this is in Example</example> public int A{
2
2555
by: sethridge1991 | last post by:
Hi Everyone, I am trying to send a XML file via SFTP staying completely in UNIX. The data in the file will vary everytime I create and send it. This is not a simple address book dump. This is what I am trying to do: 1. Access my Unix DataBase
1
6041
by: tthunder | last post by:
Hi @all, Please check the following XML file and XML schema definition below first: ------- XML File (full): ------- <?xml version="1.0" encoding="UTF-8"?>
0
10600
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10352
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10354
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
10097
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
9175
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7642
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5535
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5673
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
3835
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.