如何让 Nokogiri 了解我的命名空间? [英] How do I get Nokogiri to understand my namespaces?

查看:46
本文介绍了如何让 Nokogiri 了解我的命名空间?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下 XML 文档:

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>

我想从中获取SessionIndex(即'abcdefg')的内容.我试过这个:

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)

但我收到以下错误:

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

我已经尝试将命名空间添加到 XPath 查询中,但这并没有改变任何东西.

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

为什么我不能让 Nokogiri 相信命名空间是有效的?

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

推荐答案

看起来这个文档中的命名空间没有正确声明 - 应该有 xmlns:samlpxmlns:saml 根节点上的属性.在这种情况下,Nokogiri 本质上会忽略名称空间(因为它无法将它们映射到 URI 或 URN),因此如果您删除它们,您的 XPath 就可以工作,即

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)

这篇关于如何让 Nokogiri 了解我的命名空间?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆