如何合并属于一个xml文件的同一节点中的内容?

时间:2016-12-02 03:30:50

标签: python xml merge tags document-root

假设我有一个像这样的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'

1 个答案:

答案 0 :(得分: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