添加或替换节点和属性通过xsl转换Xml,并通过转换xsl将转换后的xml呈现在html表格中

问题描述 投票:0回答:1

我必须将 xml 文件转换为 html,添加(或替换) xml文件的特定节点和属性,通过代码 xsl。问题是:

(a) 渲染整个替换节点 连同其替换的属性,以及

(b) 原始节点也是 渲染。

我的xsl的输出是:

<p>1</p>
<p>2</p>
<p code="cc" price="33">C</p>
<p>3</p>

所需的输出必须是:

<p>1</p>
<p>2</p>
<p>33</p>

XML:

<?xml version="1.0" encoding="UTF-8"?>
<Features>
  <Feature code="a" price = "1"></Feature>
  <Feature code="b" price = "2"></Feature>
  <Feature code="c" price = "3"></Feature>
</Features>

xsl:

<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    xmlns:msxsl="urn:schemas-microsoft-com:xslt" exclude-result-prefixes="msxsl">
  <xsl:template match="@* | node()">
   <xsl:copy>
    <xsl:apply-templates select="@* | node()"/>
   </xsl:copy>
  </xsl:template>
  
  <xsl:template match="Feature[@code='c']">  
  <p code="cc" price="33">C</p>
   <xsl:apply-templates select="@*"/>
  </xsl:template>
 
  <xsl:template match="/">
    <xsl:apply-templates select="//Feature"/>
  </xsl:template>
  
  <xsl:template match="Feature">
   <xsl:apply-templates select="@price"/>
  </xsl:template>
 
  <xsl:template match="@price">
    <p><xsl:value-of select="."/> </p>
  </xsl:template>

</xsl:stylesheet>
html xml xslt
1个回答
0
投票

您只需使用以下方法即可非常简单地获得所显示的准确结果:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="html" />

 <xsl:template match="Feature">
    <p>
        <xsl:value-of select="@price" />
    </p>
</xsl:template>

<xsl:template match="Feature[@code='c']">
    <p>33</p>
</xsl:template>

</xsl:stylesheet>

但是你说你希望结果是一个 HTML 文件。所以也许你应该这样做:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="html" />
<xsl:strip-space elements="*"/>

<xsl:template match="/Features">
    <html>
        <body>
            <xsl:apply-templates/>
        </body>
    </html>
</xsl:template>

<xsl:template match="Feature">
    <p>
        <xsl:value-of select="@price" />
    </p>
</xsl:template>

<xsl:template match="Feature[@code='c']">
    <p>33</p>
</xsl:template>

</xsl:stylesheet>

获取有效的 HTML 结果,例如:

<html>
   <body>
      <p>1</p>
      <p>2</p>
      <p>33</p>
   </body>
</html>
© www.soinside.com 2019 - 2024. All rights reserved.