【问题标题】:Another issue with namespaces in xml with xpath带有 xpath 的 xml 中的命名空间的另一个问题
【发布时间】:2017-08-12 23:00:07
【问题描述】:

它对模式有效。但是我在 python 中使用 xpath 时遇到问题。

<spring:beans xmlns="http://membrane-soa.org/proxies/1/"
xmlns:spring="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.2.xsd 
  http://membrane-soa.org/proxies/1/ http://membrane-soa.org/schemas/proxies-1.xsd">

  <fileExchangeStore
    id="myFileExchangeStore"
    dir="./exchanges"
    maxDays="30" />

这部分脚本是我写的:

from lxml import etree

a = etree.parse("output.xml")

r=a.xpath('//empty:beans',
          namespaces= { 'empty':"http://membrane-soa.org/proxies/1/",
                        'spring':"http://www.springframework.org/schema/beans",
                        "xsi": "http://www.w3.org/2001/XMLSchema-instance",
                        'schemaLocation':"http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.2.xsd http://membrane-soa.org/proxies/1/ http://membrane-soa.org/schemas/proxies-1.xsd"})

现在我被这个 xpath 困住了。在这种情况下,“r”是空列表。我已经尝试了 stackoverflow 的几种解决方案,如何在 xpath 中处理命名空间,但没有成功。对于如何获取“fileExchangeSotre”内容的任何建议,我将不胜感激。

【问题讨论】:

  • fileExchangeStore 没有内容。您的意思是要获取属性值iddirmaxdays
  • 是的,这只是我的 xml 的一部分。即使那个 fileExchangeStore 没有 text 属性,但它有 tag 属性,我无法访问它
  • //fileExchangeStore/@* 匹配任何属性,//fileExchangeStore/*- 任何子节点,//fileExchangeStore//*- 任何后代节点,//fileExchangeStore/text() - 文本节点。或者你的意思是你想得到输出节点名称 - fileExchangeStore?
  • print(a.xpath('//fileExchangeStore/*')) 返回空列表,print(a.xpath('//fileExchangeStore/*')[0]) IndexError: list index out of range
  • 如果元素看起来像这样&lt;fileExchangeStore/&gt;'//fileExchangeStore/*' 将返回空列表,因为它没有子节点。你能分享你想要得到的确切输出吗?

标签: python xpath lxml xml-namespaces


【解决方案1】:

尝试使用以下代码:

namespaces= { 'empty':"http://membrane-soa.org/proxies/1/",
                    'spring':"http://www.springframework.org/schema/beans",
                    "xsi": "http://www.w3.org/2001/XMLSchema-instance",
                    'schemaLocation':"http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.2.xsd http://membrane-soa.org/proxies/1/ http://membrane-soa.org/schemas/proxies-1.xsd"}

r = a.xpath('/spring:beans/*[local-name()="fileExchange"]/@*', namespaces=namespaces)

【讨论】:

    猜你喜欢
    • 2011-01-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-22
    • 1970-01-01
    • 2012-11-22
    相关资源
    最近更新 更多