【问题标题】:What does the SQL Server XML datatype translate to in .NET and how do I convert it to XmlDocument?SQL Server XML 数据类型在 .NET 中转换为什么以及如何将其转换为 XmlDocument?
【发布时间】:2012-12-03 20:19:20
【问题描述】:

我们在数据库中有一个类型为xml 的列。我正在通过 .net SqlDataReader 阅读此信息,但我不确定将其转换为什么。

msdn 表 (http://msdn.microsoft.com/en-us/library/cc716729.aspx) 表明它属于 .net 类型 Xml,但没有 System.Xml,只有 System.Web.UI.WebControls.Xml,所以我不确定这是否正确。

所以我的问题是这样的:

当我从SqlDataReader 读取它时,我应该将SqlDbType.Xml 转换为什么,以及如何将其转换为XmlDocument

【问题讨论】:

  • 你使用的是SqlConnection还是Entity?

标签: c# .net sql-server-2005


【解决方案1】:

它转换为SqlXml,您可以从中获得XmlReaderSqlXml.CreateReader。您必须使用 SqlDataReader.GetSqlXmlmethod 来获取类型而不是字符串。

例如:

        SqlDataReader reader = cmd.ExecuteReader();
        while (reader.Read())
        {
            SqlXml xmlData =
            reader.GetSqlXml(0);
            XmlReader xmlReader = xmlData.CreateReader();

            xmlReader.MoveToContent();
            while (xmlReader.Read())
            {
                if (xmlReader.NodeType == XmlNodeType.Element)
                {
                    string elementName = xmlReader.LocalName;
                    xmlReader.Read();
                    Console.WriteLine(elementName + ": " + xmlReader.Value);
                }
            }
        }

更新:回答@Wiktor Zychla 的有用评论

这种方法的性能更好,并且在处理大型 XML 字段时可以很多因为SqlReader.GetString 将首先将字段内容加载到字符串中,而SqlReader.GetSqlXml 从创建一个 XmlReader直接流。这可以通过查看 Reflector 中的 System.Data 或类似工具来快速验证。

【讨论】:

    【解决方案2】:

    我记得将它转换为字符串。然后像往常一样使用字符串输入 XmlDocument。

    【讨论】:

    • 虽然可行,但我认为最好使用原生类型。
    • 这个判断的依据是什么?在什么意义上更好?更简单,更快,...?
    • 好吧,如果您关心这类事情,那么它是类型安全的。我希望它也会更快,因为 XmlReader 可以直接使用流,而不必先将所有内容加载到字符串中。
    • 虽然每个 XML 值都是一个字符串,但不是每个字符串都是 XML,您不同意吗?至于性能,我查看了 System.Data 代码并为您更新了答案。
    【解决方案3】:

    我自己用这个方法,用SqlCommand.ExecuteXmlReader();

    XmlDocument xdoc = new XmlDocument();
    using (SqlCommand command = new SqlCommand(queryString, connection))
    {
        XmlReader reader = command.ExecuteXmlReader();
        if (reader.Read())
        {
            xdoc.Load(reader);
        }
    }
    

    【讨论】:

    • 引用 MSDN,我认为这仅适用于“包含 XML 数据的单行单列结果集”。
    • 我猜 'XmlDocument' 变量不会将 'Xmlreader' 作为函数 Load() 的对象。
    • @A CRM - 现在可以了。使用 (System.Xml.XmlReader xmlReader = xmlData.CreateReader()) { System.Xml.XmlDocument xd = new System.Xml.XmlDocument(); xd.Load(xmlReader);返回 xd; }
    【解决方案4】:

    当然,有一个System.Xml namespace

    System.Xml 命名空间为处理 XML 提供基于标准的支持。

    不过,要使用它,您可能必须将它作为参考添加到您的项目中。微软有instructions for doing this in Visual Studio

    【讨论】:

    • 与答案无关。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-18
    • 1970-01-01
    相关资源
    最近更新 更多