Share via


How to write data from a 2-dimensional array to XML column?

Question

Saturday, August 31, 2013 8:28 PM

HI,

I'm developing a MVC3 app using c#, L2S, EF. There is a new request to write data from a 2-dimensional array to a new column (data type: xml) in a table.

The array looks like this:

StudentArray[i, 2]

The info stored in this array looks like:

{"ID", "1672"}

{"FirstName", "John"}

{"LsstName", "Smith"}

...

In my controller action, I already have this array; now how to write it into a column with data type as XML?

I'm totally new to using XML in database ... I've read  some basic on need to add "using System.Xml.Linq;";

1) can someone show me some sample code on how to write this data into this column?

2) also - How do I retrieve the data later from this column?

Thanks,

CLaudia

All replies (4)

Saturday, August 31, 2013 8:55 PM

EF doesn't support the sql xml datatype directly. it treats the xml column as a string column (the string just happens to be xml). so use any xml library you like, to produce the xml string, or parse the xml string.

note: in native sql you can update just a fragement of the xml, but with EF, to change any value, you write a new xml string.


Sunday, September 1, 2013 12:41 AM

Thanks bruce.

Do you have a few mins to provide a few lines of code, for the situation I described?

That'd be really helpful...I got the concept, but still need to know how to implement it.

Thanks,

Claudia


Tuesday, September 3, 2013 5:40 AM

hi claudia,

check this link:

http://stackoverflow.com/questions/2688445/how-to-write-two-dimensional-array-to-xml-in-scala-2-8-0

it might help you.

thx.


Tuesday, September 3, 2013 5:53 AM

Check this out:

public void SerializeMultiTest() {
    string[][] arr = { new string[] { "abc","123","easy" }, new string[] {"foobar", "baz", "xyzzy" }};
    XmlSerializer s = new XmlSerializer(typeof(string[][]));
    StringBuilder sb = new StringBuilder();
    StringWriter sw = new StringWriter(sb);
    s.Serialize(sw, arr);
    sw.Close();
    MessageBox.Show( sb.ToString());
}
 

Produces:

<?xml version="1.0" encoding="utf-16"?>
<ArrayOfArrayOfString xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <ArrayOfString>
    <string>abc</string>
    <string>123</string>
    <string>easy</string>
  </ArrayOfString>
  <ArrayOfString>
    <string>foobar</string>
    <string>baz</string>
    <string>xyzzy</string>
  </ArrayOfString>
</ArrayOfArrayOfString>