Get the names of attributes from an element in a SQL XML column

后端 未结 4 602
-上瘾入骨i
-上瘾入骨i 2021-02-06 10:36

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


 1
 
 

相关标签:
4条回答
  • 2021-02-06 10:40
    Declare @xml Xml = '<doc><a>1</a><b ba="1" bb="2" bc="3" /><c bd="3"/></doc>'
    
    Select n.value('local-name(.)', 'varchar(max)')  from @xml.nodes('/doc/*/@*') a(n)
    

    Returns ba bb bc bd

    0 讨论(0)
  • 2021-02-06 10:48
    DECLARE @xml as xml
    
    SET @xml = 
    '<doc>
     <a>1</a>
     <b ba="1" bb="2" bc="3" />
     <c bd="3"/>
    </doc>'
    
    SELECT DISTINCT
     CAST(Attribute.Name.query('local-name(.)') AS VARCHAR(100)) Attribute,
     Attribute.Name.value('.','VARCHAR(100)') Value
    FROM @xml.nodes('//@*') Attribute(Name)
    

    Returns:

    Attribute Value

    ba 1

    bb 2

    bc 3

    bd 3

    0 讨论(0)
  • 2021-02-06 10:51
    DECLARE @xml as xml
    DECLARE @path as varchar(max)
    DECLARE @index int, @count int
    
    SET @xml = 
    '<doc>
     <a>1</a>
     <b ba="1" bb="2" bc="3" />
     <c bd="3"/>
    </doc>'
    
    
    
    SELECT @index = 1
    
    SET @count = @xml.query('count(/doc/b/@*)').value('.','int')
    
    WHILE @index <= @count 
    BEGIN
        SELECT  @xml.value('local-name((/doc/b/@*[sql:variable("@index")])[1])', 'varchar(max)')
        SET @index = @index + 1
    END
    

    for element 'b'

    it returns

    • ba
    • bb
    • bc

    You can build a loop to get attributes for each element in the xml.

    BTW The XML in your sample should be closed at closing doc tag.

    0 讨论(0)
  • 2021-02-06 10:59

    this:

    declare @xml as xml
    
    set @xml = 
    '<doc>
     <a>1</a>
     <b ba="1" bb="2" bc="3" />
     <c bd="3"/>
    </doc>'
    
    select @xml.query('
        for $attr in /doc/b/@*
        return local-name($attr)') 
    

    returns:

    ba bb bc

    0 讨论(0)
提交回复
热议问题