之间取代一切如果我有一个XML标签,如:两个标签用正则表达式
<tag>
... abunch of stuff inside here
</tag>
我如何会删除里面的一切,包括标签本身?我试过re.sub('<tag>.+</tag>', '', string)
,但它不起作用。我在这里做错了什么?
之间取代一切如果我有一个XML标签,如:两个标签用正则表达式
<tag>
... abunch of stuff inside here
</tag>
我如何会删除里面的一切,包括标签本身?我试过re.sub('<tag>.+</tag>', '', string)
,但它不起作用。我在这里做错了什么?
你可以安全地做到这一点吗?与lxml
这是违背你的愿望re
但你可能已经被其他人的说服说服用re
充满危险。
import lxml.etree as etree
xml = """<root>
<item name="1"/>
<item name="2"/>
<tag>
<nested>Will I die</nested>
... abunch of stuff inside here
</tag>
<another/>
</root>"""
root = etree.fromstring(xml)
for to_kill in root.xpath("//tag"):
to_kill.getparent().remove(to_kill)
print etree.tostring(root, pretty_print=True)
给出:
<root>
<item name="1"/>
<item name="2"/>
<another/>
</root>
其实我使用XML之前的工作,但它在很久以前。我正在使用SVG,我正在处理编辑SVG。如果你想删除标签内的东西,我相信你应该在javascript或jquery中寻找你的答案。
首先,你应该学习正则表达式解析html的本质[这里](http://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags) – chuwy 2013-02-08 23:42:22