C# 从SQL获取xml属性

C# 从SQL获取xml属性,c#,xml,C#,Xml,对于SQL 2005 xml列中的此xml: <doc> <a>1</a> <b ba="1" bb="2" bc="3" /> <c bd="3"/> <doc> 我希望能够使用C windows窗体应用程序检索属性ba、bb、bc、bd的名称,而不是其中的值。在您的情况下,有两种方法可以做到这一点: 如果可以在SQL server上创建存储过程: 您可以创建一个存储过程,将XML分解为列,然后轻松地选择

对于SQL 2005 xml列中的此xml:

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

我希望能够使用C windows窗体应用程序检索属性ba、bb、bc、bd的名称,而不是其中的值。

在您的情况下,有两种方法可以做到这一点:

如果可以在SQL server上创建存储过程: 您可以创建一个存储过程,将XML分解为列,然后轻松地选择它们,并让C应用程序将其处理为一个包含列和行的表

如果你不能: 可以使用System.XML命名空间中的SqlXml在C中反汇编XML

这两种方法在这里都有很好的示例说明:

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

 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;
    }

你以前不是问过这个吗?是的,但这不是帮助我的确切答案。。。我希望我现在可以澄清一下,Salman您的Xml格式不正确,应该是在结尾,您可以跳过我为您发布的代码中的attr.Value,如果您解决了当前的Xml问题,您将获得ba、bb、bc、,如果代码中有歧义,请对其进行注释解释。其他问题中的第一个答案确切地说明了如何从XML中提取属性名称。