2017-03-24 5 views
0

以下のXMLファイルの解析に問題があります。ここに私が試したことがあります。要素ツリーを適用して複雑なxml構造体を解析する

"type:plagiarism;plagiarism_reference:00061; 
     offset:47727;length:182;source:P4P;wd_count:37" 

All art is imitation of nature.

私は本当にあなたがお勧めお願い申し上げ:

私の所望の出力

<?xml version="1.0" encoding="UTF-8" standalone="no" ?> 
<corpus name="P4P" version="1.0" lng="en" xmlns="http://clic.ub.edu/mbertran/formats/paraphrase-corpus" 
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://clic.ub.edu/mbertran/ 
formats/paraphrase-corpus http://clic.ub.edu/mbertran/formats/paraphrase-corpus.xsd"> 
    <snippets> 
     <snippet id="16488" source_description="type:plagiarism;plagiarism_reference:00061; 
     offset:47727;length:182;source:P4P;wd_count:37"> 
     All art is imitation of nature. 
     </snippet> 

    </snippets> 
</corpus> 

import xml.etree.ElementTree 
#root=xml.etree.ElementTree.parse("C:\\Users\\P4P_corpus\\P4P_corpus_v1.xml").getroot() 
source=root.findall('snippets/snippet') 
for details in source.findall: 
    print details.get('source_description') 
    print details.findtext 

私の出力が空でしたイオン。

+0

投稿されたコードの出力が空であるとは思われません。 'snippets \ snipet'は最低でもエラーを発生させるでしょう。 –

+0

@MadPhysicist、申し訳ありませんが間違った方法でスラッシュを入れて、今質問を編集します。しかし、その出力は私が得たものです。 – Boby

答えて

0

要素にxml名前空間を接頭辞する必要があります。あなたがそう「スニペット」要素を反復する

<Element '{http://clic.ub.edu/mbertran/formats/paraphrase-corpus}corpus' at 0x7ff7891f6390> 
      ^  this part here is the full name      ^

を買ってあげるの解析後にルートを印刷する場合は、最初の「スニペット」要素と「スニペット」要素

for snippets in root.findall('{http://clic.ub.edu/mbertran/formats/paraphrase-corpus}snippets'): 
    for s in snippets.findall('{http://clic.ub.edu/mbertran/formats/paraphrase-corpus}snippet'): 
     print s.get('source_description') 

を見つけ、あなたは取り扱いについて読むことができます名前空間@https://docs.python.org/2/library/xml.etree.elementtree.html#parsing-xml-with-namespaces

+0

良い解決策、それは働いた。どうもありがとう。 – Boby

関連する問題