I am simply trying to call a store procedure (SQL Server 2008) using C# and passing XMLDocument to a store procedure parameter that takes a SqlDbType.Xml data type. I am ge
To do this with an XDocument
, XElement
or other XNode
, try the following:
XDocument doc = new XDocument(
new XElement("Person",
new XAttribute("Name", "John")));
cmd.Parameters.Add("@FileContent", SqlDbType.Xml);
cmd.Parameters["@FileContent"].Value = new SqlXml(doc.CreateReader());
Other way to do it if you don't mind loosing the xml declaration (version and encoding) is just:
XML.DocumentElement.OuterXml 'where XML is a XMLDocument
you can create a XML string using following code
var doc = new XDocument();
doc.Add(new XElement("x", input.Select(x => new XElement("v", x))));
return doc.ToString();
and then pass this doc string to stored procedure as a parameter
You need to pass the xml as a string.
But if you don't need the xml functions in the database, you might consider using varbinary to store the files.
UPDATE!!!!!
Thanks. I got it to work. Added the following coded:
StringWriter sw = new StringWriter();
XmlTextWriter xw = new XmlTextWriter(sw);
doc.WriteTo(xw);
StringReader transactionXml = new StringReader(sw.ToString());
XmlTextReader xmlReader = new XmlTextReader(transactionXml);
SqlXml sqlXml = new SqlXml(xmlReader);
Converting it to a string was not enough. I got the following error: XML parsing: line 1, character 38, unable to switch the encoding”. So, I converted to string then coverted it to SqlXml and it worked.
Another simpler way is to write the xmldoc to a string and pass that to the stored procedure.
Dim sb As New StringBuilder()
Dim wrtr As New System.IO.StringWriter(sb)
doc.Save(wrtr)
Dim strxml As String = sb.ToString()
cmd.Parameters.Add("@FileContent", SqlDbType.Xml);
cmd.Parameters["@FileContent"].Value =strxml;
public static string SerializeToXml(T obj)
{
XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
ns.Add("","");
StringWriter Output = new StringWriter(new StringBuilder());
XmlSerializer ser = new XmlSerializer(obj.GetType);
ser.Serialize(Output, obj, ns);
return Output.ToString();
}