正如已经指出的那样,您的输入样本不是格式良好的 XML,因此使用 XML 解析器解析 XML 输入的标准 XPath 或 XSLT 处理链将不起作用。
但是,一些 XSLT 或 XPath 处理器允许您将 HTML 解析器而不是 XML 解析器插入到处理链中,这样您就可以解析初始输入和属性值以使用 XPath。
此外,使用 XSLT 2 和 3,您可以使用 David Carlisle 在纯 XSLT 2 https://github.com/davidcarlisle/web-xslt/blob/master/htmlparse/htmlparse.xsl 中从任何 XSLT 2 或更高版本样式表中完成的 HTML 解析器实现来解析您作为字符串的 HTML,因此可以作为字符串参数传入或在 XML 输入的 CDATA 部分中转义或使用unparsed-text 读入。
使用该 HTML 解析器的功能,您可以调用其 htmlparse 函数两次,并选择 b 元素,例如dpc:htmlparse($html-input, '', true())/div[@data-content]/dpc:htmlparse(@data-content, '', true())/b 或其内容,例如dpc:htmlparse($html-input, '', true())/div[@data-content]/dpc:htmlparse(@data-content, '', true())/b/string().
完整的 XSLT 样式表是
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:xs="http://www.w3.org/2001/XMLSchema"
xmlns:dpc="data:,dpc"
exclude-result-prefixes="#all"
version="3.0">
<xsl:import href="https://github.com/davidcarlisle/web-xslt/raw/master/htmlparse/htmlparse.xsl"/>
<xsl:param name="html-input" as="xs:string"><![CDATA[<div data-content="<i>10%</i><b>C</b>"></div>]]></xsl:param>
<xsl:template name="xsl:initial-template" match="/">
<xsl:copy-of select="dpc:htmlparse($html-input, '', true())/div[@data-content]/dpc:htmlparse(@data-content, '', true())/b/string()"/>
</xsl:template>
</xsl:stylesheet>
在线演示在
如果您依赖于 PHP 及其 XPath 1.0 支持,那么您至少能够针对使用 HTML 字符串中的loadHTML 创建的 DOMDocument 运行由 PHP 函数扩展的 XPath 1.0:
$html = <<<EOT
<div data-content="<i>10%</i><b>C</b>"></div>
EOT;
$domDoc = new DOMDocument();
$domDoc->loadHTML($html);
function parseXmlFragment($fragment) {
$docFrag = $fragment[0]->ownerDocument->createDocumentFragment();
$docFrag->appendXML($fragment[0]->textContent);
return $docFrag;
}
$xpath = new DOMXPath($domDoc);
$xpath->registerNamespace("php", "http://php.net/xpath");
$xpath->registerPHPFunctions("parseXmlFragment");
echo $xpath->evaluate("string(php:function('parseXmlFragment', //div[@data-content]/@data-content)/b)", $domDoc);
请参阅https://www.php.net/manual/en/domdocument.loadhtml.php、https://www.php.net/manual/en/domdocumentfragment.appendxml.php 和 https://www.php.net/manual/en/domxpath.registerphpfunctions.php。