views:

1120

answers:

1

How do node.XPathSelectElement() and node.XPathSelectElements() behave when the selection is either not a NodeSet or a NodeSet containing non-Elements? For example do they always return something or can they throw Exceptions? can the return value be null or is it always an IEnumerable of some sort? The XML searched is constant:

<a>
  <b c="d"/>
  <e>fgh</e>
  <e>xyz</e>
<!-- comment -->
  <b/>
</a>

To illustrate this here are some XPath strings; I would be grateful for the behaviour of both XPathSelectElement and XPathSelectElements in each case (I have put the expected XSLT NodeSet below - please comment if you disagree)

  1. //a
  2. //b
  3. //b[1]
  4. //c
  5. //@c
  6. //b | //@c
  7. //e/text()
  8. //comment()
  9. count(//b)

and expected return values

  1. 1 element
  2. 2 elements
  3. 1 element
  4. 0 elements
  5. 1 attribute node
  6. 2 elements and 1 attribute
  7. 2 text nodes
  8. 1 comment node
  9. the integer 2

If the Xpath does not return an IEnumerable of Elements (XPathSelectElements) or a single Element (XPathSelectElement) is any indication given or is the failure silent?

+1  A: 

If you inform a valid XPath expression which evaluates to XElements, you'll get:

        Linq.XPathSelectElement            Linq.XPathSelectElements
         DOM.SelectSingleNode               DOM.SelectNodes
        -----------------------            ------------------------
"//c"             null                          .Count == 0
"//a"           XElement                        .Count == 1

If you try to send a XPath matching a node type different than XElement, you'll get an InvalidOperationException; If you're not sure about XPath return and want to avoid catching Exceptions, you can go with node.XPathEvaluate()

Rubens Farias