art*_*ung 7 javascript xml xslt
我有这样的XML:
<Artist name="Syd Mead" id="3412" ntrack="28" pop="8"/>
Run Code Online (Sandbox Code Playgroud)
我需要在HTML标记中使用它:
<a href="#" data-name="Syd Mead" data-id="3412"
data-ntrack="28" data-pop="8"
class="pop-8"><span>Syd Mead</span></a>
Run Code Online (Sandbox Code Playgroud)
为最广泛的浏览器执行此操作的"正确"方法是什么?这可以通过XSLT转换可靠地完成吗?是否更好地使用正则表达式(不太可能)或者我必须解析xml,并且每个<Artist>标签读取每个属性并手动执行document.createElement和setAttribute?
该<Artist>标签是在一个父节点,有很多人.这是最好的做法吗?
这看起来像是XSLT的完美候选者 - XML干净且格式良好.如果您担心浏览器兼容性,为什么不在服务器端进行转换?
这个XSLT将转换你的数据 - 你可以在这里测试它:
来源数据:
<Artists>
<Artist name="Syd Mead" id="3412" ntrack="28" pop="8"/>
</Artists>
Run Code Online (Sandbox Code Playgroud)
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>
Run Code Online (Sandbox Code Playgroud)
我没有在客户端这样做,所以不幸的是我不能代表浏览器兼容性.
这是一个简单的(没有条件,没有额外的模板,没有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>
Run Code Online (Sandbox Code Playgroud)
在提供的XML文档上应用此转换时:
<Artist name="Syd Mead" id="3412" ntrack="28" pop="8"/>
Run Code Online (Sandbox Code Playgroud)
产生了想要的正确结果:
<a href="#" data-name="Syd Mead" data-id="3412" data-ntrack="28" data-pop="8" class="pop-8"><span>Syd Mead</span></a>
Run Code Online (Sandbox Code Playgroud)
说明:正确使用AVT(属性值模板)