簡體   English   中英

使用Python從xml解析單個文本項

[英]parsing single text items from xml with Python

我一直在嘗試從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'元素.....鍵是唯一的部分。 如何根據上方的鍵提取“值”中的文本? 即我該如何編碼key = ConnectionFile,在其下面打印值?

到目前為止,我嘗試了xml.etreexml.dom ,但均未成功。 有人可以指出我正確的方向以拉出特定的文本行-文件路徑嗎?

我已經能夠提取出唯一項的值,例如腳本中提到的ClientHostName值,但是由於它嵌套在許多類似的文件中間,因此我在努力正確地調出所需的文件路徑elements / children(對不起,我對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

這段代碼為我提供了我想要的-客戶端計算機名稱。 在拉出文件路徑時,任何建議都將不勝感激。

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安裝程序安裝,並且不會嘗試從源代碼進行編譯。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM