XPath to return default value if node not present

I had to put this into use today in a BizTalk map (inline XSLT). Since this is in BizTalk, I was limited to XPath 1.0 as a solution.

http://stackoverflow.com/questions/4489976/xpath-to-return-default-value-if-node-not-present

This is the problem/solution from StackOverflow:

Problem

Say I have a pair of XML documents

<Foo>
<Bar/>
<Baz>mystring</Baz>
</Foo>

and

<Foo>
<Bar/>
</Foo>

I want an XPath (Version 1.0 only) that returns “mystring” for the first document and “not-found” for the second.

Solution

In XPath 1.0, use:

concat(/Foo/Baz, substring(‘not-found’, 1 div not(/Foo/Baz)))

If you want to handle the posible empty Baz element, use:

concat(/Foo/Baz, substring(‘not-found’, 1 div not(/Foo/Baz[node()])))

With this input:

<Foo>
<Baz/>
</Foo>

Result: not-found string data type.

This worked beautifully!

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s