使用lxml库,拥有这个doc xml文件,我要剥离一些标签并重命名它们:doc.xml
<html>
<body>
<h5>Fruits</h5>
<div>This is some <span attr="foo">Text</span>.</div>
<div>Some <span>more</span> text.</div>
<h5>Vegetables</h5>
<div>Yet another line <span attr="bar">of</span> text.</div>
<div>This span will get <span attr="foo">removed</span> as well.</div>
<div>Nested elements <span attr="foo">will <b>be</b> left</span> alone.</div>
<div>Unless <span attr="foo">they <span attr="foo">also</span> match</span>.</div>
</body>
</html>
使用HTML代替正文,将所有内容包装在'p tag'中,而不是使用h5和每个div来包装所有内容,例如使用lxml: 我的问题是如何从一种格式以波纹管形式包装一切?
<p>
<h5 title='Fruits'>
<div>This is some <span attr='foo'>Test</span>.</div>
<div>Some<span>more</span>text.</div>
</h5>
<h5 title='Vegetables'>
<div>Yet another line <span attr='bar'>of</span>text.</div>
....
</h5>
</p>
使用lxml,剥离标签:
tree = etree.tostring(doc.xml)
tree1 = lxml.html.fromstring(tree)
etree.strip_tags(tree1, 'body')
有人对此有任何想法吗?
答案 0 :(得分:2)
<p>
标签创建一个新的文档。<body>
标记的后代。
<p>
标签的后代
<h5>
标记;将<h5>
标记添加到<p>
标记
<h5>
)答案 1 :(得分:0)
这是使用lxml的xslt解决方案。它将处理卸载到libxml。我已经在转换样式表中添加了评论:
from lxml import etree
xsl = etree.XML('''
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" indent="yes" />
<xsl:strip-space elements="*"/>
<xsl:template match="/">
<p>
<xsl:apply-templates select="html/body"/>
</p>
</xsl:template>
<!-- match body, but do not add content; this excludes /html/body elements -->
<xsl:template match="body">
<xsl:apply-templates />
</xsl:template>
<xsl:template match="h5">
<!-- record the current h5 title -->
<xsl:variable name="title" select="."/>
<h5>
<xsl:attribute name="title">
<xsl:value-of select="$title" />
</xsl:attribute>
<xsl:for-each select="following-sibling::div[preceding-sibling::h5[1] = $title]">
<!-- deep copy of each consecutive div following the current h5 element -->
<xsl:copy-of select="." />
</xsl:for-each>
</h5>
</xsl:template>
<!-- match div, but do not output anything since we are copying it into the new h5 element -->
<xsl:template match="div" />
</xsl:stylesheet>
''')
transform = etree.XSLT(xsl)
with open("doc.xml") as f:
print(transform(etree.parse(f)), end='')
如果样式表存储在文件名doc.xsl中,则使用libxml实用程序xsltproc可以实现相同的结果:
xsltproc doc.xsl doc.xml
结果:
<?xml version="1.0"?>
<p>
<h5 title="Fruits">
<div>This is some <span attr="foo">Text</span>.</div>
<div>Some <span>more</span> text.</div>
</h5>
<h5 title="Vegetables">
<div>Yet another line <span attr="bar">of</span> text.</div>
<div>This span will get <span attr="foo">removed</span> as well.</div>
<div>Nested elements <span attr="foo">will <b>be</b> left</span> alone.</div>
<div>Unless <span attr="foo">they <span attr="foo">also</span> match</span>.</div>
</h5>
</p>