如何使用xsl从xml节点获取CDATA?

Vij*_*ade 6 xml xslt cdata

我试图CDATA使用XSL 获取XML节点的内容.该节点目前看起来像这样:

<node id="1" text="Book Information" ><![CDATA[This is sample text]]></node>
Run Code Online (Sandbox Code Playgroud)

我需要这This is sample text件作品.有没有人对此有任何想法?

提前致谢.

Owe*_* S. 10

好吧,如果我使用这个样式表:

<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:output method="text"/>
  <xsl:template match="node/text()">
    <xsl:copy/>
  </xsl:template>
</xsl:stylesheet>
Run Code Online (Sandbox Code Playgroud)

在这个XML文件上:

<?xml version="1.0" encoding="utf-8"?>
<node id=1 text="Book Information" ><![CDATA[This is sample text]]></node>
Run Code Online (Sandbox Code Playgroud)

我得到一个解析错误,因为id=1XML无效.

在属性值(id="1")周围加上引号并重新运行样式表,我得到输出:

这是示例文本

所以有一个开始.基本上,只需将CDATA视为文本节点,即可开始使用.

你说:

我找到了类似的内容:
<xsl:output cdata-section-elements="text"/>
然后获取CDATA:
<xsl:value-of select="node" />

如果你也使用这种方法就可以了value-of.这将是您的评论中的一个示例,value-of而不是使用.但请注意,它cdata-section-elements仅适用于输出端,指示要将哪些输出 XML元素打印为CDATA节而不是普通的旧字符数据.它与获取数据无关.

<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:output cdata-section-elements="foo"/>
  <xsl:template match="/">
    <foo>
      <xsl:value-of select="node"/>
    </foo>
  </xsl:template>
</xsl:stylesheet>
Run Code Online (Sandbox Code Playgroud)

打印出来

<?xml version="1.0"?>
<foo><![CDATA[This is sample text]]></foo>
Run Code Online (Sandbox Code Playgroud)

  • 张贴一段您想做的事以及您希望价值流向何方? (2认同)

Vij*_*ade 1

实现此目的的其他一些简单步骤;\n
使用W3cschools编辑器进行尝试。\n
示例 XML 文件:

\n\n
<?xml version="1.0" encoding="ISO-8859-1"?>\n<!-- Edited by XMLSpy\xc2\xae -->\n<catalog>\n    <cd>\n        <disk id="title"><![CDATA[Sample xml]]></disk >\n        <disk id="artist"><![CDATA[Vijay]]></disk >\n    </cd>\n</catalog>\n
Run Code Online (Sandbox Code Playgroud)\n\n


\n示例 XSL 文件:

\n\n
<?xml version="1.0" encoding="ISO-8859-1"?>\n<!-- Edited by XMLSpy\xc2\xae -->\n<xsl:stylesheet version="1.0"\nxmlns:xsl="http://www.w3.org/1999/XSL/Transform">\n<xsl:template match="/">\n  <html>\n  <body>\n    <h2>My CD Collection</h2>\n    <table border="1">\n      <tr bgcolor="#9acd32">\n        <th>Title</th>\n        <th>Artist</th>\n      </tr>\n<xsl:for-each select="catalog/cd">\n\n      <tr>\n       <td><xsl:value-of select="/catalog/cd/disk[@id=\'title\']"/></td>\n       <td><xsl:value-of select="/catalog/cd/disk[@id=\'artist\']"/></td>\n       </tr>\n</xsl:for-each>\n    </table>\n  </body>\n  </html>\n</xsl:template>\n</xsl:stylesheet>\n
Run Code Online (Sandbox Code Playgroud)\n\n


\n最终结果是;\n
\n替代文本

\n