2 回答
TA贡献1851条经验 获得超3个赞
创建一个只有标签的新文档。
<p>
迭代
<body>
原始文档中标记的后代。如果遇到
<h5>
标签;将<h5>
标签添加到<p>
标签并将后续标签作为后代添加到它(
<h5>
)将标签从原始文档添加到新文档 - 作为其
<p>
标签 的后代
TA贡献1789条经验 获得超10个赞
这是使用 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>
添加回答
举报