Search code examples
sqlsql-serverxmlt-sql

SQL XML How to query specific node


I'm playing around with SQL and XML. I have a column in our database (properties) where XML is stored.

An example of this XML looks like this:

<root xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="http://www.xyz.de/activerepository/fileprops">
  <props>
    <prop ns="ARM:" elem="_NoFilter">
      <value xsi:type="xsd:boolean">true</value>
    </prop>
    <prop ns="DAV:" elem="displayname">
      <value xsi:type="xsd:string">Some text in it</value>
    </prop>
    <prop ns="DAV:" elem="getcontenttype">
      <value xsi:type="xsd:string">message/rfc822</value>
    </prop>
    <prop ns="DAV:" elem="creationdate">
      <value xsi:type="xsd:dateTime">2017-01-02T09:38:28.1278078</value>
    </prop>
  </props>
</root>

I've written a query, where I get all props of this XML structure.

;WITH XMLNAMESPACES(DEFAULT 'http://www.xyz.de/activerepository/fileprops')
SELECT 
    cast(properties as xml).query('root/props/prop'),
    *
FROM   tm_cas_files (nolock)
where  id = 'A7ED7D99-8CDB-47F6-8EF5-18E7FCB97F28'

This query works fine, but I get all nodes of the XML structure.

The result of this query looks like this:

<p1:prop xmlns:p1="http://www.xyz.de/activerepository/fileprops" ns="ARM:" elem="_NoFilter">
  <p1:value xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="xsd:boolean">true</p1:value>
</p1:prop>
<p2:prop xmlns:p2="http://www.xyz.de/activerepository/fileprops" ns="DAV:" elem="displayname">
  <p2:value xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="xsd:string">Some text in it</p2:value>
</p2:prop>
<p3:prop xmlns:p3="http://www.xyz.de/activerepository/fileprops" ns="DAV:" elem="getcontenttype">
  <p3:value xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="xsd:string">message/rfc822</p3:value>
</p3:prop>
<p4:prop xmlns:p4="http://www.xyz.de/activerepository/fileprops" ns="DAV:" elem="creationdate">
  <p4:value xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="xsd:dateTime">2017-01-02T09:38:28.1278078</p4:value>
</p4:prop>

How can I get now only a specific node of this XML?

I've already tested this query (to get i.e. "_NoFilter" node), but this SQL query returns no / empty result:

;WITH XMLNAMESPACES(DEFAULT 'http://www.xyz.de/activerepository/fileprops')
SELECT 
    cast(properties as xml).query('root/props/prop[elem="_NoFilter"]'),
    *
FROM   tm_cas_files (nolock)
where  id = 'A7ED7D99-8CDB-47F6-8EF5-18E7FCB97F28'

Solution

  • If you just want the _NoFilter node, you can use XPath to select only this one.

    /root/props/prop[@elem="_NoFilter"]
    

    or maybe even

    /root/props/prop[@elem="_NoFilter"]/value
    

    shorthand:

    //prop[@elem="_NoFilter"]/value