1

我们有一堆文件是 html 页面,但其中包含额外的 xml 元素(都以我们的公司名称“TLA”为前缀)为我现在正在重写的旧程序提供数据和结构。

示例表格:

<html >
<head>
    <title>Highly Simplified Example Form</title>
</head>
<body>
    <TLA:document xmlns:TLA="http://www.tla.com">
        <TLA:contexts>
            <TLA:context id="id_1" value=""></TLA:context>
        </TLA:contexts>
        <TLA:page>
            <TLA:question id="q_id_1">
                <table>
                    <tr>
                        <td>
                            <input id="input_id_1" type="text" />
                        </td>
                    </tr>
                </table>
            </TLA:question>
        </TLA:page>
        <!-- Repeat many times -->
    </TLA:document>
</body>
</html>

我的任务是编写一个预处理器,它将提取所有“TLA”元素并忽略 html 元素

所需的 XML 输出:

<?xml version="1.0" encoding="utf-8" ?>
<TLA:document xmlns:TLA="http://www.tla.com">
    <TLA:contexts>
      <TLA:context id="id_1" value=""></TLA:context>
    </TLA:contexts>
    <TLA:page>
      <TLA:question  id="q_id_1">
      </TLA:question>
    </TLA:page>
    <!-- Repeat many times -->
</TLA:document>

这对于 XSLT 应该是可行的,但我无法制定正确的代码。这是我到目前为止所拥有的:

<?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"
    xmlns:tla="http://www.tla.com"
>
    <xsl:output method="xml" indent="yes"/>

    <xsl:template match="tla:*">
      <xsl:copy>
        <xsl:apply-templates select="@*|node()"/>
      </xsl:copy>
    </xsl:template>
</xsl:stylesheet>

这是提取我想要的元素(但不是它们的属性!),但也提取了 html 元素的文本属性和内容。如何排除 html 元素及其内容?

4

2 回答 2

3

这应该这样做:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    xmlns:tla="http://www.tla.com">
  <xsl:output method="xml" indent="yes" omit-xml-declaration="yes" />
  <xsl:strip-space elements="*" />

  <xsl:template match="text()" />

  <xsl:template match="tla:* | tla:*/@* | tla:*/text()">
    <xsl:copy>
      <xsl:apply-templates select="@*|node()"/>
    </xsl:copy>
  </xsl:template>
</xsl:stylesheet>

在您的示例输入上运行时(一旦添加了缺少的命名空间声明),结果是:

<TLA:document xmlns:TLA="http://www.tla.com">
  <TLA:contexts>
    <TLA:context id="id_1" value="" />
  </TLA:contexts>
  <TLA:page>
    <TLA:question id="q_id_1" />
  </TLA:page>
</TLA:document>
于 2013-04-04T14:51:46.987 回答
2

你可以试试这样的...

XSLT 1.0

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

    <xsl:template match="@*|node()">
        <xsl:apply-templates select="@*|node()"/>
    </xsl:template>

    <xsl:template match="tla:*">
        <xsl:copy>
            <xsl:copy-of select="@*"/>
            <xsl:apply-templates select="node()"/>
        </xsl:copy>
    </xsl:template>

</xsl:stylesheet>
于 2013-04-04T14:35:49.023 回答