Link to home
Avatar of yolish
yolish

asked on

Loading XML Document

I am trying to load an xml document that has the following format

<System>
  <sysinfo>
    <account>1</account>
  </sysinfo>
  <order>
    <mark>12</mark>
  </order>
  <detail>
     <marking>12-2</marking>
  </detail>
  <order>
    <mark>13</mark>
  </order>
  <detail>
     <marking>13-2</marking>
  </detail>
</system>

I am trying to load this into SQL Server. I have a SPROC that can handle the loading, my problem is getting the XML document into the SQL Server SPROC.

I have done a lot of research and have read use a DataSet, etc... but need some help on the VB.net part of things... Any and all help would be appreciated.

Thanks,
-t
Avatar of LordWabbit
LordWabbit

here you go, will need to change the insert to cater for your specific table etc.  also might want to put the code in a loop if you are inserting multiple files

        Dim myReader As New System.IO.StreamReader("C:\eatme\xml.doc")
        Dim strXml As String = myReader.ReadToEnd()
        myReader.Close();
        Dim myConnection As New SqlConnection(strConnectionString)
        myConnection.Open()
        Dim myCommand As New SqlCommand("Insert INTO XmlTable (xmlColumnName) Values (@xmlData)", myConnection)
        myCommand.Parameters.AddWithValue("@xmlData", strXml)
        myCommand.ExecuteNonQuery()
        myCommand.Dispose()
        myConnection.Close()
        myConnection.Dispose()

please not that your xml example is not well formed and sql will throw an exception (closing tag should be </System> xml is case sensitive)  also might be a good idea to create an xsd and assign it to the xml column which will check if the right elements are present in the xml when you insert it into the xml column
Avatar of yolish

ASKER

Wabbit... Looks good, still have a few questions

1) What is the parameter @xmlData?
2) Lets say I want to enter information into an Orders table that has both the Account (sysinfo) & Mark(order)?

thanks
ASKER CERTIFIED SOLUTION
Avatar of LordWabbit
LordWabbit

Blurred text
THIS SOLUTION IS ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
See Pricing Options
Start Free Trial
Avatar of yolish

ASKER

LordWabbit-

Good answer... had to make 1 small change
add
myCommand.CommandType = CommandType.StoredProcedure