使用C#将XML直接保存到数据库

时间:2010-06-07 17:42:50

标签: c# xml database visual-studio-2010 dataset

这是我的xml文件的一部分

<teams>
  <team-profile>
    <name>Australia</name>
    <id>1</id>
    <stats type="Test">
      <span>1877-2010</span>
      <matches>721</matches>
      <won>339</won>
      <lost>186</lost>
      <tied>2</tied>
      <draw>194</draw>
      <percentage>47.01</percentage>
    </stats>
    <squad>
      <player id="135" fullname="Shane Warne"/>
      <player id="136" fullname="Damien Martyn"/>
      <player id="138" fullname="Michael Clarke"/>
    </squad>
  </team-profile>
</team>

我在某处读过有一种方法可以将这种XML直接保存到数据库中。我正在使用VS2010。我已经为这个xml所需的数据创建了数据集。有没有办法直接在数据集上映射这个XML? 还有其他想法吗? 我还必须将一些其他更复杂的XML文件保存到数据库中。

我已尝试过xsd.exe为此XML创建xsd架构。

1 个答案:

答案 0 :(得分:3)

SQL Server 2005+有一个本机XML数据类型,如果你创建一个列,你可以简单地插入该列,这里有一个类似于你的insert,这个表的第二列的数据类型是xml

INSERT INTO docs VALUES (1, '<book genre="security"
publicationdate="2002" ISBN="0-7356-1588-2">
   <title>Writing Secure Code</title>
   <author>
      <first-name>Michael</first-name>
      <last-name>Howard</last-name>
   </author>
   <author>
      <first-name>David</first-name>
      <last-name>LeBlanc</last-name>
   </author>
   <price>39.99</price>
</book>')
INSERT INTO docs VALUES (2, 
'<doc id="123">
    <sections>
   <section num="1"><title>XML Schema</title></section>
   <section num="3"><title>Benefits</title></section>
   <section num="4"><title>Features</title></section>
    </sections>
</doc>')