1

I have this XPath expression, which sum all nodes in the deepest XML hierarchy, without using nodes names:

select  @data.value('sum(//*[not(*)])', 'float')

How do I make an exception of one node, by its name?

Say this is the xml:

<c>
  <b1>
    <a>1</a>
    <d>4</d>
    <g>5</g>
 </b1>
 <b1>
   <a>7</a>
   <d>1</d>
   <g>2</g>
 </b1>
</c>

I would like the sum to contain "d" and "g", without "a", but "a" will be pass as parameter and so need to be represented as parameter inside the expression. I've tried the following:

declare @except varchar(max) = 'a'


select  @data.value('sum(//*[not(*)])', 'float') - @data.value('sum(//*:local-name()=sql:variable("@except"))', 'float')

but no success.

2 Answers 2

2

While Marc's answer is what i would do mostly, I have a small hack for you, below

select  @data.value('sum(//*[not(*)])', 'float')- @data.value('sum(//*:a)', 'float')
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you, it works fine. I added just another little requirement. Be happy if you would adjust by it.
I think there's no place for creating another question on this. Please try to adjust your answer by my last requirement. Thanks
1

You could parse the XML into name and value in a CTE, and then select from that CTE - something like this:

DECLARE @Data XML = '...(your XML here).....';

;WITH XmlCte AS
(
    SELECT
        NodeName = xc.value('local-name(.)', 'varchar(25)'),
        NodeValue = xc.value('(.)[1]', 'int')
    FROM 
        @Data.nodes('/c/b1/*') AS XT(XC)
)
SELECT SUM(x.NodeValue)
FROM XmlCte x
WHERE x.NodeName <> '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.