合并标签(从字符串列表)一起

问题描述:

如果在列表[1]我有两个字符串,包含两个XML标签:合并标签(从字符串列表)一起

<example> this is cool</example> 

<example> this is cooler! </example> 

我怎么能合并两个标签到一个单一的一个,所以它看起来是这样的:

<example> this is cool this is cooler! </example> 

所以,当我做印刷(名单[1])我得到:

<example> this is cool this is cooler! </example> 
+0

所以,你有两个字符串列表? – brandizzi 2015-01-26 19:54:05

+0

@brandizzi我有一个元素的列表,里面的元素有一个单一的字符串“这很酷这是更酷!” – Jorge 2015-01-26 19:55:25

+3

如果你说你有“标签”,我问什么样的标签? BeautifulSoup? ElementTree的? minidom命名?你使用的是什么xml/html分析器? – 2015-01-26 19:56:06

我们必须找到标签名称和两个XML元素的文本。要做到这一点,最好的办法是解析的元素。

所以,你有这样一个列表,对吗?

>>> l = ['<example>this is cool</example>', '<example>this is cooler</example>'] 

首先,让我们解析它(在这种情况下,与lxml):

>>> import lxml.etree 
>>> elements = [lxml.etree.fromstring(s) for s in l] 

现在我们有两个元素的列表。从这些元素中,我们可以把他们的标签名称...

>>> elements[0].tag 
'example' 

...及其文本内容:

>>> elements[0].text 
'this is cool' 
>>> elements[1].text 
'this is cooler' 

好了,我们可以创建一个新的解析相同标签的元作为第一个:

>>> new_element = new_element = lxml.etree.Element(elements[0].tag) 

现在,我们这个新元素的文本设置为前两者的串联:

>>> new_element.text = elements[0].text + elements[1].text 

现在,我们得到的字符串表示从元素对象:

>>> lxml.etree.tostring(new_element) 
b'<example>this is coolthis is cooler</example>' 
+0

我有用一个简单的元素列表:“这是很酷的‘与’这是冷却器‘都是列表[1]有可能是名单内的任何数量的’”标签的[1] – Jorge 2015-01-26 20:06:31

+1

嗯...灿您是否看到如何修改下面的代码以适应您的情况? – brandizzi 2015-01-26 20:07:54

+0

不是当可以有任何数量的标签 – Jorge 2015-01-26 20:08:29