我有这样的
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?
<艺术家>标签位于父节点中,其中有很多.这是最好的做法吗?
解决方法
这看起来像是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>
我没有在客户端这样做,所以不幸的是我无法代表浏览器兼容性.