[英]lxml Python, read text and tree for given structure of XML file
我正在嘗試在Node下獲取文本和ID,請參見此處的示例文件: example.xml
但是,它沒有普通XML文件的結構。 結構如下:
<TextWithNodes><Node id="0"/>
<Node id="1"/>
<Node id="2"/>9407011<Node id="9"/>
<Node id="10"/>ACL<Node id="13"/> <Node id="14"/>1994<Node id="18"/>
<Node id="19"/> Lg.Pr.Dc <Node id="29"/>
我想要的輸出是start_node
, end_node
和text_between_node
的列表。 我不確定是否可以使用lxml
庫來做到這一點。
目前,我使用
from lxml import etree
tree = etree.parse('9407011.az-scixml.xml')
nodes = tree.xpath('//TextWithNodes')[0].getchildren()
node = nodes[0] # example one node
print(node.text) # this give empty string because you don't have closing same id
使用XPath可能適合您。 將normalize-space()
與空字符串進行比較將消除沒有后續文本的節點。
這可能對您有用:
from lxml import etree as ET
root = ET.XML(b'''<?xml version='1.0' encoding='UTF-8'?>
<GateDocument version="3">
<TextWithNodes><Node id="0"/>
<Node id="1"/>
<Node id="2"/>9407011<Node id="9"/>
<Node id="10"/>ACL<Node id="13"/> <Node id="14"/>1994<Node id="18"/>
<Node id="19"/> Lg.Pr.Dc <Node id="29"/>
</TextWithNodes></GateDocument>''')
# Grab each 'Node' element:
# Only if the element has an 'id' attribute, and only if
# the first sibling is a text node that isn't
# all wihtespace and only if
# the second sibling is a 'Node' with an 'id'
for r in root.xpath('''//Node[@id]
[following-sibling::node()
[1]
[self::text()]
[normalize-space() != ""]]
[following-sibling::node()
[2]
[self::Node[@id]]]'''):
# All elements that satisfy that above XPath should
# also satisfy the requirements for the next line
print (r.get('id'), repr(r.tail), r.getnext().get('id'))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.