我需要在HTML标记中使用它:Syd Mead对">
我有这样的XML:
<Artist name="Syd Mead" id="3412" ntrack="28" pop="8"/>
我需要在HTML标记中使用它:
<a href="#" data-name="Syd Mead" data-id="3412"
data-ntrack="28" data-pop="8"
class="pop-8"><span>Syd Mead</span></a>
对于最广泛的浏览器来说,什么是“正确”的方法呢?这可以通过XSLT转换可靠地完成吗?是使用正则表达式更好(不太可能),还是必须解析出xml,并为每个<Artist>
标记读取每个属性并手动执行document.createElement和setAttribute?
<Artist>
标签在父节点中,有很多这样的标签。有没有这方面的最佳实践?
发布于 2012-06-07 05:28:09
这看起来是XSLT的完美候选者-- XML是干净的、格式良好的。如果你关心浏览器的兼容性,为什么不在服务器端进行转换呢?
这个XSLT将转换您的数据-您可以对其进行here测试
源数据:
<Artists>
<Artist name="Syd Mead" id="3412" ntrack="28" pop="8"/>
</Artists>
XSLT:
<?xml version="1.0" encoding="ISO-8859-1"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="/">
<xsl:for-each select="Artists/Artist">
<a href="#">
<xsl:attribute name="data-id">
<xsl:value-of select="@id"/>
</xsl:attribute>
<xsl:attribute name="data-ntrack">
<xsl:value-of select="@ntrack"/>
</xsl:attribute>
<xsl:attribute name="data-pop">
<xsl:value-of select="@pop"/>
</xsl:attribute>
<xsl:attribute name="data-name">
<xsl:value-of select="@name"/>
</xsl:attribute>
<xsl:attribute name="class">
<xsl:value-of select="concat('pop-',@pop)"/>
</xsl:attribute>
<span><xsl:value-of select="@name"/></span>
</a>
</xsl:for-each>
</xsl:template>
</xsl:stylesheet>
我没有在客户端做到这一点,所以不幸的是,我不能谈论浏览器的兼容性。
发布于 2012-06-07 12:36:04
这里是一个简单的转换(没有条件,没有额外的模板,没有xsl:attribute
**,没有** xsl:for-each
**),**:
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output omit-xml-declaration="yes" indent="no"/>
<xsl:template match="Artist">
<a href="#" data-name="{@name}"
data-id="{@id}"
data-ntrack="{@ntrack}"
data-pop="{@pop}"
class="pop-{@pop}">
<span><xsl:value-of select="@name"/></span>
</a>
</xsl:template>
</xsl:stylesheet>
在所提供的XML文档上应用此转换时的:
<Artist name="Syd Mead" id="3412" ntrack="28" pop="8"/>
生成所需的正确结果
<a href="#" data-name="Syd Mead" data-id="3412" data-ntrack="28" data-pop="8" class="pop-8"><span>Syd Mead</span></a>
Explanation:正确使用 (属性值模板)
发布于 2012-06-07 06:51:11
下面是我认为更简单的另一个XSLT样式表选项:
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="html"/>
<xsl:template match="/*/Artist">
<a href="#" class="pop-{@pop}">
<xsl:apply-templates select="@*"/>
<span><xsl:value-of select="@name"/></span>
</a>
</xsl:template>
<xsl:template match="@*">
<xsl:attribute name="data-{name()}">
<xsl:value-of select="."/>
</xsl:attribute>
</xsl:template>
</xsl:stylesheet>
XML输入
<Artists>
<Artist name="Syd Mead" id="3412" ntrack="28" pop="8"/>
</Artists>
HTML输出
<a class="pop-8" href="#" data-name="Syd Mead" data-id="3412" data-ntrack="28" data-pop="8">
<span>Syd Mead</span>
</a>
https://stackoverflow.com/questions/10925970
复制相似问题