2016-12-02 50 views
0

比方說,我有一個XML文件是這樣的:如何合併屬於一個xml文件的同一節點中的內容?

<recs> 
<REC> 
<SYS_TOPIC>topic1 topic1</SYS_TOPIC> 
<SYS_AUTHORS>author1</SYS_AUTHORS> 
<DOC_CONTENT>content1 content1 content1 content1 content1 content1 content1</DOC_CONTENT> 
<DOC_WRITEDATE>2016-12-01 09:30:10</DOC_WRITEDATE> 
</REC> 

<REC> 
<SYS_TOPIC>topic2 topic2</SYS_TOPIC> 
<SYS_AUTHORS>author2</SYS_AUTHORS> 
<DOC_CONTENT>content2 content2 content2 content2 content2 content2 content1</DOC_CONTENT> 
<DOC_WRITEDATE>2016-12-01 09:30:10</DOC_WRITEDATE> 
</REC> 
</recs> 

如果我想在<DOC_CONTENT>一起在一個標籤合併所有的內容?我試過root.findall('DOC_CONTENT').text但是它的調音臺'list' object has no attribute 'text'

+0

你能給一個需要輸出的例子嗎? –

+0

@nick_gabpe我想要這樣: ' content1 content1 content1 content1 content1 content1 content2 content2 content2 content2 content1'只要把中的所有內容放在同一個標​​記中就好了! – Jess

回答

0
import xml.etree.ElementTree as et 

source_xml = """<recs> 
<REC> 
<SYS_TOPIC>topic1 topic1</SYS_TOPIC> 
<SYS_AUTHORS>author1</SYS_AUTHORS> 
<DOC_CONTENT>content1 content1 content1 content1 content1 content1 content1</DOC_CONTENT> 
<DOC_WRITEDATE>2016-12-01 09:30:10</DOC_WRITEDATE> 
</REC> 

<REC> 
<SYS_TOPIC>topic2 topic2</SYS_TOPIC> 
<SYS_AUTHORS>author2</SYS_AUTHORS> 
<DOC_CONTENT>content2 content2 content2 content2 content2 content2 content1</DOC_CONTENT> 
<DOC_WRITEDATE>2016-12-01 09:30:10</DOC_WRITEDATE> 
</REC> 
</recs>""" 
tree = et.fromstring(source_xml) 
doc_content = "DOC_CONTENT" 
content = [tr.text for tr in tree.iter() if (tr.tag ==doc_content)] 
root = et.Element(doc_content) 
root.text = "" 
for el in content: 
    root.text += el 
+0

謝謝你的回答!我嘗試過這個!但爲什麼會出現名稱錯誤:'NameError:name'root'未定義' 謝謝! – Jess

+0

因爲我忘了添加行'root = et.Element(doc_content)'。 它應該現在工作。 –

+0

完美謝謝你! – Jess

相關問題