Diamantis Sellis
Diamantis Sellis

Reputation: 45

xpath to find a node with optional attribute

I would like to search across multiple XML files for nodes with an optional attribute. The files missing the attribute I am looking for do not declare the namespace it belongs. I am searching using a simple XPath as in the following example:

Here I am interested in the other_attribute of node:

<?xml version="1.0" encoding="UTF-8"?>
<otherfile xmlns:xs="something" xmlns:optional="something_else">
  <node attribute = "hohoho" optional:other_attribute= "mary Xmass">
  </node>
</otherfile>

And I am matching it using the XPath //@optional:other_attribute. However, when trying to do the same in the following file:

<?xml version="1.0" encoding="UTF-8"?>
<file xmlns:xs="something">
    <node attribute = "hohoho">
    </node>
</file>

The search fails because the namespace optional is not declared in the second example file. Is there a way to do a conditional search for the attribute with using the Xpath syntax?

Upvotes: 0

Views: 305

Answers (2)

DonnyFlaw
DonnyFlaw

Reputation: 690

This should work

//@*[name()="optional:other_attribute"]

Upvotes: 1

Jack Fleeting
Jack Fleeting

Reputation: 24930

If I understand you correctly, the easiest way to do this is to switch the expression to local-name(). With the expression

//*[@*/local-name()="other_attribute"]

would select the correct node in the first example and select no nodes in the other.

Upvotes: 0

Related Questions