使用 Python 的 libxml2 从 XML 节点读取文本 [英] Reading text from XML nodes using Python's libxml2
问题描述
我是第一次 XPath
用户,需要能够获取这些不同元素的文本值.. 例如 time
、title
等.我在 Python 中使用 libxml2
模块,到目前为止还没有多少运气只获得我需要的文本的值.下面的代码只返回元素标签..我需要这些值..任何帮助将不胜感激!
I am a first time XPath
user and need to be able to get the text values of these different elements.. for instance time
, title
, etc.. I am using the libxml2
module in Python and so far have not had much luck getting just the values of the text I need. The code below here only returns the element tags.. i need the values.. any help would be GREATLY appreciated!
我正在使用此代码:
doc = libxml2.parseDoc(xmlOutput)
result = doc.xpathEval('//*')
使用以下文件:
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE SCAN_LIST_OUTPUT SYSTEM "https://qualysapi.qualys.com/api/2.0/fo/sca/scan_list_output.dtd">
<SCAN_LIST_OUTPUT>
<RESPONSE>
<DATETIME>2012-01-22T01:21:53Z</DATETIME>
<SCAN_LIST>
<SCAN>
<REF>scan/2343423</REF>
<TYPE>Scheduled</TYPE>
<TITLE><![CDATA[customer 1 5/20/2012]]></TITLE>
<USER_LOGIN>user1</USER_LOGIN>
<LAUNCH_DATETIME>2012-02-21T04:11:05Z</LAUNCH_DATETIME>
<STATUS>
<STATE>Finished</STATE>
</STATUS>
<TARGET><![CDATA[13.3.3.2, 13.8.8.10, 13.10.12.60, 13.10.12.11...]]></TARGET>
</SCAN>
</SCAN_LIST>
</RESPONSE>
</SCAN_LIST_OUTPUT>
推荐答案
您可以对每个返回的 xmlNode
对象调用 getContent()
以检索关联的文本.请注意,这是递归的 —— 要以非递归方式访问 libxml2 中的文本内容,您需要检索元素下的关联文本节点,并在 that<上调用 .getContent()
/em>.
You can call getContent()
on each returned xmlNode
object to retrieve the associated text. Note that this is recursive -- to non-recursively access text content in libxml2, you'll want to retrieve the associated text node under the element, and call .getContent()
on that.
也就是说,如果您使用 lxml.etree
(一个更高级别的 Python API,仍然支持 C libxml2 库)而不是 Python libxml2,这会更容易;在这种情况下,只需 element.text
即可将相关内容作为字符串访问.
That said, this would be easier if you used lxml.etree
(a higher-level Python API, still backing into the C libxml2 library) instead of the Python libxml2; in that case, it's simply element.text
to access the associated content as a string.
这篇关于使用 Python 的 libxml2 从 XML 节点读取文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!