views:

20

answers:

2

Here's a question about repeated nodes and missing values.

Given the xml below is there a way in XPath of returning (value2, null, value5) rather than (value2, value5)? I'm using an expression that looks like:

/nodes/node[*]/value2/text()

To retrieve the values. I need to know there's a value missing and at which indexes this occurs. I'm a complete newby to XPath and cannot figure out how to do this.

<nodes>
  <node>
    <value1>value1</value1>
    <value2>value2</value2>
  </node>
  <node>
    <value1>value3</value1>
  </node>
  <node>
    <value1>value4</value1>
    <value2>value5</value2>
  </node>
</nodes>

Kind regards,

mipper

+1  A: 

I suspect you'll need to get friendly with your xml parser and iterate over the nodes yourself. This example is in Ruby; I decorated it with comments since I don't know what languages you can read.

#!/usr/bin/ruby1.8

require 'nokogiri'

xml = <<EOS
<nodes>
  <node>
    <value1>value1</value1>
    <value2>value2</value2>
  </node>
  <node>
    <value1>value3</value1>
  </node>
  <node>
    <value1>value4</value1>
    <value2>value5</value2>
  </node>
</nodes>
EOS

# Parse the xml with Nokogiri
doc = Nokogiri::XML(xml)

# Get an array of nodes
nodes = doc.xpath('/nodes/node')

# For each node, get its value.  Put the collected values into the
# "values" array.
values = nodes.collect do |node|
  node.at_xpath('value2/text()').to_s
end

# Print the values in a programmer-friendly format
p values     # => ["value2", "", "value5"]
Wayne Conrad
A: 

Given the xml below is there a way in XPath of returning (value2, null, value5)

In XPath, no. XPath can only select/return existing nodes. It does not know null.

In XSLT or any other XML aware programming language the problem can be solved by iteration.

<xsl:for-each select="/nodes/node">
  <xsl:value-of select="*[2]" />
  <xsl:text>, </xsl:text>
</xsl:for-each>
Tomalak