【问题标题】:Searching XML using XPath returning no nodes使用 XPath 搜索 XML,不返回节点
【发布时间】:2016-02-23 19:59:02
【问题描述】:

我一定遗漏了一些非常明显的东西,我终于放弃了试图找出问题所在。我正在尝试搜索一段简单的 XML 以查找所有 <Parent> 节点。我正在使用 R 3.2.2 和 XML 包。这是带有示例 XML 的代码:

library(XML)

example_xml <- paste(
  '<?xml version="1.0"?>',
    '<GetProductCategoriesForASINResponse xmlns="http://mws.amazonservices.com/schema/Products/2011-10-01">',
      '<GetProductCategoriesForASINResult>',
        '<Self>',
          '<ProductCategoryId>11056341</ProductCategoryId>',
          '<ProductCategoryName>Chicken</ProductCategoryName>',
          '<Parent>',
            '<ProductCategoryId>11056281</ProductCategoryId>',
            '<ProductCategoryName>Dog</ProductCategoryName>',
            '<Parent>',
              '<ProductCategoryId>11055991</ProductCategoryId>',
              '<ProductCategoryName>Monkey</ProductCategoryName>',
              '<Parent>',
                '<ProductCategoryId>11055981</ProductCategoryId>',
                '<ProductCategoryName>Frog</ProductCategoryName>',
                '<Parent>',
                  '<ProductCategoryId>3760911</ProductCategoryId>',
                  '<ProductCategoryName>Iguana</ProductCategoryName>',
                '</Parent>',
              '</Parent>',
            '</Parent>',
          '</Parent>',
        '</Self>',
      '</GetProductCategoriesForASINResult>',
    '<ResponseMetadata>',
      '<RequestId>abs123</RequestId>',
    '</ResponseMetadata>',
    '</GetProductCategoriesForASINResponse>',
    sep = ''
)

categories_xml <- xmlTreeParse(example_xml, useInternalNodes = TRUE)
root <- xmlRoot(categories_xml)
category_nodes <- getNodeSet(root, '//Parent')

我希望category_nodes 包含 4 个节点,但它返回的是 0。

【问题讨论】:

  • 在定义xpath 时,您必须考虑命名空间(文件的第二行具有xmlns=... 属性)。如果您手动删除该属性,您的代码将获得所需的输出。
  • 不能手动删除怎么办?我从 API 调用中得到这个,我不想手动从字符串中解析出来。
  • 试试这个:category_nodes &lt;- getNodeSet(root, '//as:Parent', namespaces = c(as="http://mws.amazonservices.com/schema/Products/2011-10-01"))
  • @bergant 你应该发布一个答案。也许getNodeSet(root, '//as:Parent', namespaces = c(as=xmlNamespace(root))) 可以更优雅。
  • 谢谢@nicola。 xmlNamespace(root) 更优雅。其实我在找一个副本。我认为stackoverflow.com/questions/24954792/… 非常接近?

标签: xml r xpath


【解决方案1】:

您必须在 xpath 表达式中使用带有命名空间的元素:

getNodeSet(root, '//as:Parent', namespaces = c(as="http://mws.amazonservices.com/schema/Products/2011-10-01"))

正如 nicola 所指出的,您可以从元素中获取命名空间,从而为您提供:

getNodeSet(root, '//as:Parent', namespaces = c(as=xmlNamespace(root)))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-10-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多