Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations TouchToneTommy on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

XQuery: XML data in SQL Server 1

Status
Not open for further replies.

robz2009

Programmer
Apr 20, 2009
41
GB
I'm trying to use Xquery to extract specific info from XML tags but I can't get it to work, all I get is a NULL result. I don't know if the problem is with how the source XML is formed or my xquery statement.

My statement is,

DECLARE @xml xml
SELECT @xml = PasswordPolicy FROM role

SELECT
ppd.value('PasswordLengthMin[1]','int')
FROM @xml.nodes('//PasswordPolicy') pp(ppd)

The xml being populated into @xml is,

<PasswordPolicy xmlns:xsi=" xmlns:xsd="<PasswordLengthMin xmlns="urn:travelex.global.enterprise.service">7</PasswordLengthMin>
<PasswordLengthMax xmlns="urn:travelex.global.enterprise.service">50</PasswordLengthMax>
</PasswordPolicy>

If someone can help me out, thanks.
 
Have a go with:

DECLARE @xml XML
SELECT @xml = '<PasswordPolicy xmlns:xsi=" xmlns:xsd="<PasswordLengthMin xmlns="urn:travelex.global.enterprise.service">7</PasswordLengthMin>
<PasswordLengthMax xmlns="@xml">50</PasswordLengthMax>
</PasswordPolicy>' ;

WITH XMLNAMESPACES ( 'urn:travelex.global.enterprise.service' AS a )
SELECT x.y.value('a:passwordLengthMin[1]', 'VARCHAR(50)')
FROM @xml.nodes('/PasswordPolicy') AS x ( y ) ;

SELECT x.y.value('.', 'VARCHAR(50)')
FROM @xml.nodes('
declare namespace a="urn:travelex.global.enterprise.service";
//a:passwordLengthMin[1]') AS x ( y ) ;
 
That works thanks, I'd like to understand the solution also.

Why do you have two select statements? What is the difference between one and another?
 
You have also changed the text being populated in my @xml variable?

The tag for PasswordLengthMax has changed from.

<PasswordLengthMax xmlns="urn:travelex.global.enterprise.service">50</PasswordLengthMax>

to,

<PasswordLengthMax xmlns="@xml">50</PasswordLengthMax>

Please explain so I can understand this, thanks.
 
ooops this

Code:
<PasswordLengthMax xmlns="@xml">50</PasswordLengthMax>
should not have changed, it should be as you had it. typo on my part. it should be:
Code:
<PasswordLengthMax xmlns="urn:travelex.global.enterprise.service">50</PasswordLengthMax>

The two solutions are just different ways to specify the namespace that you are using. Either by using the WITH syntax, or by declaring a default.

A decent couple of articles that will help you with extra examples:



There are lots of different ways to get to the same result in xml.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top