How can you get the atomic value of an element in a typed xml column if you can't use text() on it?
This query;
-- Add schema
CREATE XML SCHEMA COLLECTION MySchema AS N'<xs:schema xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xs="http://www.w3.org/2001/XMLSchema"
attributeFormDefault="unqualified"
elementFormDefault="qualified"
xmlns="http://mynamespace"
targetNamespace="http://mynamespace">
<xs:element name="element1" type="element1Type">
</xs:element>
<xs:complexType name="element1Type">
<xs:sequence minOccurs="0" maxOccurs="unbounded">
<xs:element name="element2" type="element2Type" />
</xs:sequence>
</xs:complexType>
<xs:complexType name="element2Type">
<xs:sequence>
<xs:element name="element3" type="element3Type" minOccurs="0" maxOccurs="unbounded" />
</xs:sequence>
</xs:complexType>
<xs:complexType name="element3Type">
<xs:sequence minOccurs="0">
<xs:element minOccurs="0" name="element4" />
</xs:sequence>
</xs:complexType>
</xs:schema>'
GO
-- Create table
CREATE TABLE [dbo].[MyTable](
[XmlColumn] [xml](CONTENT [dbo].[MySchema]) NOT NULL
)
GO
-- Add test data
INSERT INTO MyTable SELECT N'<element1 xmlns="http://mynamespace" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<element2>
<element3>
<element4>my text here</element4>
</element3>
</element2>
</element1>'
GO
-- run query
WITH XMLNAMESPACES(
'http://mynamespace' as s,
DEFAULT 'http://mynamespace'
)
SELECT
T.rows.value('(element3/element4)[1]/text()', 'varchar(100)') as [AtomicValue]
FROM
MyTable
CROSS APPLY
XmlColumn.nodes('/element1/element2') T(rows)
Results in;
XQuery [MyTable.XmlColumn.value()]: 'text()' is not supported on simple typed or
'http://www.w3.org/2001/XMLSchema#anyType' elements, found
'element({http://mynamespace}:element4,xs:anyType) ?'.
I've read this, but mass-editing the schema on every atomic value I want to be able to read feels like overkill...
You can use query and then value.
WITH XMLNAMESPACES(
'http://mynamespace' as s,
DEFAULT 'http://mynamespace'
)
SELECT
T.rows.query('element3/element4').value('.', 'varchar(100)')
FROM
MyTable
CROSS APPLY
XmlColumn.nodes('/element1/element2') T(rows)
Or you can specify the type of element4 in the schema.
<xs:element minOccurs="0" name="element4" type="xs:string"/>
and use this query
WITH XMLNAMESPACES(
'http://mynamespace' as s,
DEFAULT 'http://mynamespace'
)
SELECT
T.rows.value('(element3/element4)[1]', 'varchar(100)') as [AtomicValue]
FROM
MyTable
CROSS APPLY
XmlColumn.nodes('/element1/element2') T(rows)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With