views:

1253

answers:

2

I have the following XML document:

<samlp:LogoutRequest ID="123456789" Version="2.0" IssueInstant="200904051217">
  <saml:NameID>@NOT_USED@</saml:NameID>
  <samlp:SessionIndex>abcdefg</samlp:SessionIndex>
</samlp:LogoutRequest>

I'd like to get the content of the SessionIndex (that is, 'abcdefg') out of it. I've tried this:

XPATH_QUERY = "LogoutRequest[@ID][@Version='2.0'][IssueInstant]/SessionIndex"
SAML_XMLNS  = 'urn:oasis:names:tc:SAML:2.0:assertion'
SAMLP_XMLNS = 'urn:oasis:names:tc:SAML:2.0:protocol'

require 'nokogiri'
doc = Nokogiri::XML(xml)
doc.xpath(XPATH_QUERY, 'saml' => SAML_XMLNS, 'samlp' => SAMLP_XMLNS)

but I get the following errors:

Nokogiri::XML::SyntaxError: Namespace prefix samlp on LogoutRequest is not defined
Nokogiri::XML::SyntaxError: Namespace prefix saml on NameID is not defined
Nokogiri::XML::SyntaxError: Namespace prefix samlp on SessionIndex is not defined

I've tried adding the namespaces to the XPath query, but that doesn't change anything.

Why can't I convince Nokogiri that the namespaces are valid?

+2  A: 

It doesn't look like the namespaces in this document are correctly declared - there should be xmlns:samlp and xmlns:saml attributes on the root node. In cases like this, Nokogiri essentially ignores the namespaces (as it can't map them to URIs or URNs), so your XPath works if you remove them, i.e.

doc.xpath(XPATH_QUERY)
Greg Campbell
That seems to give me the same errors ... in some situations. Doing it literally in irb works fine, but running my specs still blows up. Garr.
James A. Rosen
Got it! Nokogiri returns an "error" node that wraps the node that it found, but it _really_did_find_the_node_!
James A. Rosen
A: 

I see a two different options for you:

  1. Remove all the namespaces

    nokogiri.org/Nokogiri/XML/Document.html#method-i-remove_namespaces%21

    Brute force way of doing it. Could lead to problems where there are namespace collisions.

  2. Use collect_namespaces

    http://nokogiri.org/Nokogiri/XML/Document.html#method-i-collect_namespaces

    A much better solution. You could use this once to identify the namespaces (say in irb) and hard-code them.

    OR

    Use it at runtime, and supply it as the second argument to nokogiri.org/Nokogiri/XML/Node.html#method-i-xpath

Jamie Cobbett