0

I am trying to get to a node in XML using SQL Server.

CREATE TABLE temp.testXML(ID INT, xmlinput XML NULL);

INSERT INTO temp.testXML 
VALUES (1, '<root><node1><lang>English</lang></node1><innernode><info>20170117T022113</info></innernode></root>')

I want to print "info" node i.e "20170117T022113"

SELECT 
    t.id,
    x.XmlCol.value('(/innernode/info)[1]', 'VARCHAR(100)') AS dt
FROM 
    [temp].[testxml] as t
CROSS APPLY 
    t.rawxml.nodes('/root') as x(XmlCol)

I am getting a null.

How can I get to the node value??

Thanks MR

1 Answer 1

1

There are two mistakes in your query

  • Use xmlinput column name in nodes function instead rawxml
  • Remove the first / in value function

Query

SELECT t.id,
       x.XmlCol.value('(innernode/info)[1]', 'VARCHAR(100)') AS dt
FROM   [testxml] AS t
       CROSS APPLY t.xmlinput.nodes('/root') AS x(XmlCol) 
Sign up to request clarification or add additional context in comments.

4 Comments

I had one more clarification, when do you use '/' and when don't you use. Thanks so much
@user2726975 - Am not a expert in xml but I have seen in value method start with / when XQuery(first parameter) starts with root. Something like value('(/root/innernode/info)[1]', 'VARCHAR(100)' )
@user2726975 But in simple words: 1-slash = move one level down, 2-slashes=*find any node below*, no slash = relative to the context node. You start to navigate at the root, than you move down (and up/to the side) the path. The current position is the context node. Any path starts from there. In the very beginning the root node is the context node. Here you'll find a comprehensive overview
@Shnugo - Thanks.. TBH it was helpful to me in understanding

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.