Mechanize / Nokogiri 无法使用 xpath 解析 XML

Mechanize / Nokogiri failing to parse XML with xpath

我从 API 收到一个 xml 文件。 我正在尝试使用 Mechanize 将其作为 XML 文件接收。 底层是Nokogiri。 无论我做什么,我似乎都无法使用任何 xpath 变量将它变成 return 任何东西。 它似乎可以很好地识别 xml 文件,即它以 Mechanize::XmlFile 的形式出现,并在我使用 Nokogiri 时显示元素。

我可以运行。

xml.at("/")

并得到响应,但任何其他 .at 或 .search 我 运行 return 都没有。 例如

xml.at("//Duration")

下面是一个示例响应。

@body =
"<JobSearchResults xmlns:i=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns=\"http://schemas.aspiremediagroup.net/jobboard/1.0/Beta\"><Duration>P0DT0H0M0.328S</Duration><JobCount>0</JobCount><JobIDs /><Jobs /><PageCount>0</PageCount><PageNo>0</PageNo><PageSize>20</PageSize><ProximityStats i:nil=\"true\" /><RoleSuggestions><String>ADDING</String></RoleSuggestions><Search><AccountGroupIDs i:nil=\"true\" /><AccountIDs i:nil=\"true\" /><ExcludeUnknownSalaries>false</ExcludeUnknownSalaries><Industries i:nil=\"true\" /><JobIDsOnly>false</JobIDsOnly><JobTypes><ID>Any</ID></JobTypes><Locations><Location><Country>GBR</Country><ID i:nil=\"true\" /><Latitude i:nil=\"true\" /><Longitude i:nil=\"true\" /><ParentLocation i:nil=\"true\" /><Text i:nil=\"true\" /></Location></Locations><MaxAge i:nil=\"true\" /><MaxDistance>25</MaxDistance><Page>1</Page><PageSize>20</PageSize><Role>adgqeg</Role><Salaries i:nil=\"true\" /><Skills i:nil=\"true\" /><SortOrder>OVERALL_SCORE_DESC</SortOrder></Search><SkillsSuggestions><String i:nil=\"true\" /></SkillsSuggestions><Started>2016-06-29T08:53:18.2215898Z</Started><ThisPageSize>0</ThisPageSize></JobSearchResults>"

知道为什么这不起作用吗?

好像是运行

xml.remove_namespaces!

修复了该问题并允许使用 // 样式的 xpath 变量搜索文档。

我怀疑有比现有解决方案更好的解决方案。

我个人更喜欢 .css 选项:

xml.css("Duration")

也可以使用:

xml.at_css("Duration")

可在此处找到更多信息:http://www.nokogiri.org/tutorials/searching_a_xml_html_document.html