xpath query query

D

David Gordon

Hi Folks,

I wonder if anyone can help me with the following (perhaps trivial) problem:

<xml>
<node name="a" type="a"/>
<node name="b" type=""/>
<node name="c"/>
<node name="d" type="b"/>
</xml>

we're using a command line xpath script to pluck values from
configuration files, e.g. to get the list of node names:

xpath test.xml '/xml/node/@name'

Returns the list of names in the file, easy.
a
b
c
d

Because of the way our other command line tools work, we're relying on
the result being a return separated list. We can get the list of types
like this:

xpath test.xml '/xml/node/@type'

which returns

a

b

But passes over the node with no type attribute. Is there an xpath query
which would give the result:

a


b

So where no type attribute existed, an empty string is returned?

thanks in advance,

David Gordon
 
D

David Carlisle

David Gordon said:
<xml>
<node name="a" type="a"/>
<node name="b" type=""/>
<node name="c"/>
<node name="d" type="b"/>
</xml>

xpath test.xml '/xml/node/@type'

which returns

a

b

But passes over the node with no type attribute. Is there an xpath query
which would give the result:

a


b

So where no type attribute existed, an empty string is returned?

Since you are using Xpath1 (rather than xpath2 or xslt for example)
You have to return nodes that exist in the source, in document order,
or return a single atomic value such as a string.
So in this case you would need to return some node to repreentthe
missing type on c and that node must occur between th etype attribute on
b and the type attribute on c. The only possiblities really then are the
node <node name="c"/> or the white space text nodes either side of that.
Given that your XPath tool outputs attribute nodes @type as just (for
example) "a" I assume it prints the string value of a node, which is
empty for <node name="c"/>, which is what you want, so..

/xml/node/@type|/xml/node[not(@type)]

returns a node set of all type attribute nodes, and all node element
nodes that don't have a type attribute.
With a bit of luck your xpath tool will output that node set by printing
the string value of each node, in document order, but i can't test that.

David
 
D

David Gordon

...
With a bit of luck your xpath tool will output that node set by printing
the string value of each node, in document order, but i can't test that.

I can test it, and I did, and... it worked!

Genius - thanks very much :)

David
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,734
Messages
2,569,441
Members
44,832
Latest member
GlennSmall

Latest Threads

Top