2017-02-17 5 views
0

のテキストやツリーをお読みください。しかし、それは通常のXMLのような構造を持っていませんexample.xmllxmlのPythonの、ここではサンプルファイルを参照、私はノードの下のテキストとIDを取得しようとしている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_nodeend_nodetext_between_nodeのリストです。私はそれを行うためにlxmlライブラリを使用できるかどうかはわかりません。

現在、私はXPathはあなたのために働くかもしれない使用

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 
+0

あなたの試みと掲載サンプルまたはリンクを使用して、目的の結果を表示してください。 – Parfait

答えて

1

を使用しています。 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')) 
+0

これは魅力のように動作します、ありがとうRob! – titipata

関連する問題