Calling a Stored Procedure with XML Datatype

前端 未结 9 1113
旧巷少年郎
旧巷少年郎 2021-01-05 07:06

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

相关标签:
9条回答
  • 2021-01-05 07:43

    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());
    
    0 讨论(0)
  • 2021-01-05 07:49

    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
    
    0 讨论(0)
  • 2021-01-05 07:51

    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

    0 讨论(0)
  • 2021-01-05 07:52

    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.

    0 讨论(0)
  • 2021-01-05 07:54

    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;
    
    0 讨论(0)
  • 2021-01-05 07:55
    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();
    }
    
    0 讨论(0)
提交回复
热议问题