我们有一堆文件是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元素及其内容?
答案 0 :(得分: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>
答案 1 :(得分: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>