c# - 从 SQL 获取 xml 属性

标签 c# xml

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

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

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

最佳答案

尝试这样的事情 - 第一种方法将从数据库中加载 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;
    }

关于c# - 从 SQL 获取 xml 属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4237588/

相关文章:

c# - 问题为元素 'ImageParameters' 不能包含子元素 'ImageParameter'

c# - Entity Framework 将原始 SQL 查询绑定(bind)到模型类

c# - 使用 Web 服务时出错,内容类型 "application/xop+xml"与预期类型 "text/xml"不匹配

c# - 使用 dll 中的 ViewModel 进行 UserControl

xml - 获取xml元素在SQL Server 2012中的位置

python - 我可以让 Beautiful Soup 保持属性排序和行缩进吗

c# - 在 C# 中将 string.Empty 转换为(通用)T?

c# - 如何为 winforms 实现双击右键?

xml - Jenkins:指标 'JUnit' 的结果文件无效。结果文件已被跳过

java - 如何在 Spring 解决多部分解析器? java.lang.NoClassDefFoundError : org/apache/commons/fileupload/FileItemFactory