从 SQL 获取 xml 属性 [英] getting xml attributes from SQL

查看:32
本文介绍了从 SQL 获取 xml 属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于这个 xml(在 SQL 2005 XML 列中):

For this xml (in a SQL 2005 XML column):

<doc> 
 <a>1</a> 
 <b ba="1" bb="2" bc="3" /> 
 <c bd="3"/> 
<doc> 

我希望能够使用 C# windows 窗体应用程序检索属性的名称(ba、bb、bc、bd)而不是内部的值.

I'd like to be able to retrieve the names of the attributes (ba, bb, bc, bd) rather than the values inside using C# windows form application.

推荐答案

试试这样——第一种方法会从数据库加载 XML 字符串(调整连接字符串并查询到自己的数据库、服务器、表、列名称),第二种方法将根据您对上一个问题的回答将从数据库加载的 XML 字符串解析为属性名称列表:

Try something like this - the first method will load the XML string from the database (adjust the connection string and query to your own database, server, table, column names), and the second method will parse the XML string loaded from the database into a list of attribute names based on the answer you got for your previous question:

 static void Main(string[] args)
    {
        string xmlContent = GrabStringFromDatabase(1);
        List<string> attributeNames = ParseForAttributeNames(xmlContent);

        Console.WriteLine("Your XML attributes are: {0}", string.Join(",", attributeNames.ToArray()));
    }

    private static string GrabStringFromDatabase(int ID)
    {
        string result = string.Empty;
        string connection = "server=(local);database=test;integrated security=SSPI";
        string query = "SELECT XmlContent FROM dbo.TestXml WHERE ID = @ID";

        using(SqlConnection _con = new SqlConnection(connection))
        using (SqlCommand _cmd = new SqlCommand(query, _con))
        {
            _cmd.Parameters.Add("@ID", SqlDbType.Int).Value = ID;

            _con.Open();
            result = _cmd.ExecuteScalar().ToString();
            _con.Close();
        }

        return result;
    }

    private static List<string> ParseForAttributeNames(string xmlContent)
    {
        List<string> attributeNames = new List<string>();

        XDocument xmlDoc = XDocument.Parse(xmlContent);

        var nodeAttrs = xmlDoc.Descendants().Select(x => x.Attributes());

        foreach (var attrs in nodeAttrs)
        {
            foreach (var attr in attrs)
            {
                attributeNames.Add(attr.Name.LocalName);
            }
        }

        return attributeNames;
    }

这篇关于从 SQL 获取 xml 属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆