使用Python从XML中解析单个文本项
我一直在尝试从我的 XML 文件中提取一个特定的文本项,这个文本项位于某个元素的子元素中。下面是我的 XML 内容。
<PropertySetProperty xsi:type="typens:PropertySetProperty">
<Key>ConnectionFile</Key>
<Value xsi:type="xs:string">THE TEXT I WANT, IN THIS CASE A FILE PATH</Value>
</PropertySetProperty>
问题是,有大约 8 个不同的 'propertysetproperty' 元素……其中的键是独一无二的部分。我该如何根据上面的键提取下面的 Value 文本呢?也就是说,我该怎么写代码,让它在键等于 ConnectionFile 时,打印出它下面的值?
到目前为止,我尝试过 xml.etree
和 xml.dom
,但都没有成功。有没有人能告诉我该怎么做,才能提取出特定的文本行——也就是文件路径?
我已经能够提取出一些独特项目的值,比如我脚本中提到的 ClientHostName 值,但我在如何正确调用我需要的文件路径上遇到了困难,因为它嵌套在这么多相似的元素/子元素中(抱歉,我对 XML 的术语有点生疏)。
import xml.etree
import xml.etree.ElementTree as ET
xml = '//xmlfile'
tree = ET.parse(xml)
root = tree.getroot()
for origin in root.iter('ClientHostName'):
print origin.text
这段代码给了我我想要的——客户端计算机名称。关于如何提取文件路径的建议非常感谢。
1 个回答
0
xmlstr = """
<?xml version="1.0"?>
<RootElement>
<PropertySetProperty>
<Key>KeyNotOfInterest</Key>
<Value>ValueNotOfInterest</Value>
</PropertySetProperty>
<PropertySetProperty>
<Key>ConnectionFile</Key>
<Value>THE TEXT I WANT, IN THIS CASE A FILE PATH</Value>
</PropertySetProperty>
<PropertySetProperty>
<Key>KeyAlsoNotOfInterest</Key>
<Value>ValueAlsoNotOfInterest</Value>
</PropertySetProperty>
</RootElement>
"""
from lxml import etree
doc = etree.fromstring(xmlstr.strip())
#doc = etree.parse("xmlfilename.xml")
xp = "//PropertySetProperty[Key/text()='ConnectionFile']/Value/text()"
wanted = doc.xpath(xp)[0]
print wanted
或者可以使用带参数的xpath:
xp = "//PropertySetProperty[Key/text()=$key]/Value/text()"
wanted = doc.xpath(xp, key="ConnectionFile")[0]
这个XPath的意思是:
“在文档中找到名为PropertSetProperty的元素,里面有一个子元素Key,且这个子元素的文本值是'ConnectionFile',然后获取子元素Value的文本值。”
这假设你已经安装了lxml
:
$ pip install lxml
在Windows上最好使用:
$ easy_install lxml
因为这样会通过下载的exe安装程序来安装,而不会尝试从源代码编译。