首页 > 解决方案 > 如何使用 saxonc.PySaxonProcessor 获取 XML 元素的属性值

问题描述

我正在使用Windows 10 中的Saxon-C-1.2.0分析在 Python 3.8 中使用 Saxon XSLT 处理。

我可以成功运行脚本 SaxonHEC.1.2.0.\Saxon.C.API\python-saxon**saxon_example.py**。

最后打印行显示获取属性值的结果。我认为该代码中有错误。

我的问题:如何获取 XML 属性的值?

with saxonc.PySaxonProcessor(license=False) as proc:
   # ... code left out form saxon_example.py

   xml2 = """\
<out>
  <person att1='value1' att2='value2'>text1</person>
  <person>text2</person>
  <person>text3</person>
</out>
"""
   node2 = proc.parse_xml(xml_text=xml2)
   outNode = node2.children  
   children = outNode[0].children

   attrs = children[1].attributes
   if len(attrs) == 2:
       print('node.children[1].attributes[1].string_value =', attrs[1].string_value)
       print('node.children[1].attributes[1]              =', attrs[1])
       print('node.children[1].attributes[1].__str__      =', attrs[1].__str__())
       print('node.children[1].attributes[1].__repr__     =', attrs[1].__repr__())
       print('node.children[1].attributes[1].text         =', attrs[1].text)

在命令行我得到:

node.children[1].attributes[1].string_value = att2="value2"
node.children[1].attributes[1]              = att2="value2"
node.children[1].attributes[1].__str__      = att2="value2"
node.children[1].attributes[1].__repr__     = att2="value2"
Traceback (most recent call last):
  File "test-app.py", line 77, in <module>
    print('node.children[1].attributes[1].text         =', attrs[1].text)
AttributeError: 'saxonc.PyXdmNode' object has no attribute 'text'

而我希望只看到"value2"没有属性名称。

标签: python

解决方案


正如评论中提到的,请参阅指向错误问题的链接,其中我们提到了对错误的修复:string_value属性应该调用底层 C++ 方法getStringValue。修复在下一个维护版本中可用。

get_attribute_value如果您知道属性的名称,另一种解决方法是使用该函数。


推荐阅读