2

i m reading an xml, but i have a problem when i want to read it without its inner(child) tags. for example:

DECLARE @XMLToParse  XML

SET @XMLToParse =   '<Animals>
                       <LandAnimals>
                        <Animal>Baboon</Animal>
                        <Animal>Yak
                            <d>asd</d>
                        </Animal>
                        <Animal>Zebra</Animal>
                       </LandAnimals>
                    </Animals>'

SELECT  xmlData.A.value('.', 'VARCHAR(100)') AS Animal
FROM    @XMLToParse.nodes('Animals/LandAnimals/Animal') xmlData(A)

this query extracts on the second record 'Yak asd', but i need only 'Yak'. how can i fix it?

thank you.!

2 Answers 2

2

Change your call on .value() to get the text():

SELECT  xmlData.A.value('(./text())[1]', 'VARCHAR(100)') AS Animal
FROM    @XMLToParse.nodes('Animals/LandAnimals/Animal') xmlData(A)
Sign up to request clarification or add additional context in comments.

3 Comments

thank you very much! and so, are there any others options ilke 'text()'?
@user3061212 What other options? You might use strange work-arounds but why?
@user3061212 The /text() is the content which is the real textual content of an element. Reading the . with .value() will read the entire tree below the context node. You might read about .value('data(...)') if this is your intention. But in your case you are just not interested in lower elements...
2

Specify text()

SELECT  xmlData.A.value('./text()[1]', 'VARCHAR(100)') AS Animal
FROM    @XMLToParse.nodes('Animals/LandAnimals/Animal') xmlData(A)

Comments

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.