英文:
Inserting a new root element in lxml
问题
我有一个XML文件(不一定是HTML):
<div>
<p>...</p>
</div>
我希望插入一个新的html根元素,使其变为:
<html>
<div>
<p>...</p>
</div>
</html>
(稍后我会添加head和body)。是否有一个简单的命令可以在不创建新树和复制元素的情况下将新元素html插入div的新父级?
英文:
I have an xml file (not necessarily html):
<div>
<p>...</p>
</div>
and I wish to insert a new html root element to give
<html>
<div>
<p>...</p>
</div>
</html>
(I will add head, body later.) Is there a simple command to insert a new element html as new parent of div without creating a new tree and copying elements?
答案1
得分: 1
当你创建一个 html 元素并将 div 放入其中时:
>>> import lxml.etree as et
>>> t = et.fromstring("<div><p>...</p></div>")
<Element div>
>>> html = et.Element("html")
<Element html>
>>> html.append(t)
>>> et.tostring(html)
b'<html><div><p>...</p></div></html>'
>>>
英文:
Sure; just create a html element and add the div inside it:
>>> import lxml.etree as et
>>> t = et.fromstring("<div><p>...</p></div>")
<Element div>
>>> html = et.Element("html")
<Element html>
>>> html.append(t)
>>> et.tostring(html)
b'<html><div><p>...</p></div></html>'
>>>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论