我有这个xml代码:
<title xml:lang="ar">?????</title>
<title xml:lang="en">English</title>
Run Code Online (Sandbox Code Playgroud)
我在xsl格式化:
<div class="title">
<xsl:value-of select="root/title"/>
</div>
Run Code Online (Sandbox Code Playgroud)
然而,这^只显示阿拉伯语标题,而不是英语标题.我试过这段代码:
<div class="title">
<xsl:attribute name="xml:lang"><xsl:value-of select="root/title"/> </xsl:attribute>
</div>
Run Code Online (Sandbox Code Playgroud)
但是使用这个^代码,它根本不显示标题.显示英语和阿拉伯语标题的正确方法是什么?
以下将有效.
源XML:
$xmlDoc = <<< XML
<titles>
<title xml:lang="ar">?????</title>
<title xml:lang="en">English</title>
</titles>
XML;
Run Code Online (Sandbox Code Playgroud)
带有模板的XSL样式表,匹配文档中的任何标题节点
$xslDoc = <<< XSL
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="/">
<h1>Titles</h1>
<xsl:apply-templates/>
</xsl:template>
<xsl:template match="title">
<div class="{@xml:lang} title">
<xsl:value-of select="."/>
</div>
</xsl:template>
</xsl:stylesheet>
XSL;
Run Code Online (Sandbox Code Playgroud)
用PHP进行转换:
$xml = new DOMDocument();
$xml->loadXML($xmlDoc);
$xsl = new DOMDocument;
$xsl->loadXML($xslDoc);
$proc = new XSLTProcessor;
$proc->importStyleSheet($xsl);
echo $proc->transformToXML($xml);
Run Code Online (Sandbox Code Playgroud)
会给:
<?xml version="1.0"?>
<h1>Titles</h1>
<div class="ar title">?????</div>
<div class="en title">English</div>
Run Code Online (Sandbox Code Playgroud)
编辑:修改标题模板以使用xml:lang属性作为类属性,因此您可以使用CSS设置样式.如果您需要更复杂的样式,请编写与该属性匹配的另一个模板(如Volker所示).