emdog4
emdog4

Reputation: 2015

Xpath return node relative to another node

I have done a search for all nodes that have an attribute containing (substring) a String. These nodes can be found at different levels of the tree, sometimes 5 or 6 levels deep. I'd like to know what parent/ancestor node they correspond to at a specified level, 2 levels deep. The result for the search only should be much greater than the results for the corresponding parents.

EDIT to include code: /xs:schema/xs:element/descendant::node()/@*[starts-with(., 'my-search-string-here')]

EDIT to clarify my intent:

When I execute the Xpath above sometimes the results are

/xs:schema/xs:element/xs:complexType/xs:attribute or /xs:schema/xs:element/xs:complexType/xs:sequence/xs:element or /xs:schema/xs:element/xs:complexType/xs:complexContent/xs:extension/xs:sequence/xs:element

These results indicate a place in the Schema where I have added application specific code. However, I need to remove this code now. I'm building an "adapter" schema that will redefine the original Schema (untouched) and import my schema. The String I am searching for is my prefix. What I need is the @name of the /xs:schema/node() in which the prefix is found, so I can create a new schema defining these elements. They will be imported into the adapter and redefine another schema (that I'm not supposed to modify).

To reiterate, I need to search all the attributes (descendants of /xs:schema/xs:element) for a prefix, and then get the corresponding /xs:schema/xs:element/@name for each of the matches to the search.

Upvotes: 1

Views: 324

Answers (3)

emdog4
emdog4

Reputation: 2015

As Eric mentioned, I need to change my thought process to select the xs:elements which contain a node with a matching attribute rather than select the matching attributes of descendant nodes of xs:elements, then work back up. This is critical. However, the code sample he posted to select the attributes does not work, we need to use another solution.

Here is the code that works to select an element that contains and attribute containing* (substring) a string.

/xs:schema/child::node()[descendant::node()/@*[starts-with(., 'my-prefix-here')]]

Upvotes: 0

Emiliano Poggi
Emiliano Poggi

Reputation: 24826

To reiterate, I need to search all the attributes (descendants of /xs:schema/xs:element) for a prefix, and then get the corresponding /xs:schema/xs:element/@name for each of the matches to the search.

 /
 xs:schema/
  xs:element
  [descendant::*/@*[starts-with(., 'my-search-string-here')]]/
   @name

Upvotes: 1

Eric
Eric

Reputation: 97631

This should do it:

/xs:schema/xs:element[starts-with(descendant::node()/@*, 'my-search-string-here')]

You want to think of it as

select the xs:elements which contain a node with a matching attribute

rather than

select the matching attributes of descendant nodes of xs:elements, then work back up

Upvotes: 1

Related Questions