Home > Software design >  Xpath cannot check passing attribute using namespace
Xpath cannot check passing attribute using namespace

Time:02-06

Using this xpath exercise code:

<datasource formatted-name='Activity' inline='true' source-platform='win' version='18.1' xmlns:user='http://www.tableausoftware.com/xml/user'>
  <column datatype='integer' name='[Number of Records]' role='measure' type='quantitative' user:auto-column='numrec'>
    <calculation class='tableau' formula='1' />
  </column>
</datasource>

I want to extract @name, but only if the attribute user:auto-column exists.

All I could come up with is:

  1. //column[@auto-column]/@name
  2. //column[@user:auto-column]/@name
  3. //column[@auto-column=user:column[@auto-column]]/@name

The 1st one worked in only one of xpath testers I found online, the rest of them didn't work at all.

I have looked everywhere I could (read questions here on stackoverflow, checked out tutorials/documentation/questions on w3schools, microsoft, ibm, xpath testers, tutorials and cheetsheets) and tried to solve for hours.

How can I select the @name of column elements that have @user:auto-column?

CodePudding user response:

Note that the attribute @user:auto-column is bound to a namespace. The user prefix is declared on the element above: xmlns:user='http://www.tableausoftware.com/xml/user'.

The first XPath shouldn't have worked, unless the XPath tester you were using simply ignored all namespaces and processed namespace-unaware.

The second XPath in your list is what you would want to use, in order to address that namespace-qualified attribute:

//column[@user:auto-column]/@name

However, you need to ensure that the namespace for the user prefix is declared and available in the context of whatever you are using to execute the XPath.

Otherwise, you would want to look for a namespace agnostic means of matching and filtering just on the local-name(). For instance:

//column[@*[local-name() = 'auto-column']]/@name

Now, because it is only filtering by the local-name() of the attribute, you run the risk of matching elements that have a similar attribute name that is bound to a totally different namespace, not the tableau namespace. That is probably unlikely, but just for awareness.

  •  Tags:  
  • Related