========= 更新 =========
非常感谢 Tomalak 提供了正确的 XSL 语法,并感谢 Ian Roberts 指出为了在我的 XSLT 中使用名称空间,我需要在一开始就在我的 DocumentBuilderFactory 中调用“setNamespaceAware(true)”。
========= 结束更新 =========
问:如何编写一个 XSLT 样式表来过滤掉“ http://foo.com/abc ”命名空间中的所有元素和/或所有节点树?
我有一个如下所示的 XML 文件:
源 XML:
<zoo xmlns="http://myurl.com/wsdl/myservice">
<animal>elephant</animal>
<exhibit>
<animal>walrus</animal>
<animal>sea otter</animal>
<trainer xmlns="http://foo.com/abc">Jack</trainer>
</exhibit>
<exhibit xmlns="http://foo.com/abc">
<animal>lion</animal>
<animal>tiger</animal>
</exhibit>
</zoo>
期望的结果 XML:
<zoo xmlns="http://myurl.com/wsdl/myservice">
<animal>elephant</animal>
<exhibit>
<animal>walrus</animal>
<animal>sea otter</animal>
</exhibit>
</zoo>
XSLT(感谢 Tomalak):
<xsl:stylesheet version="2.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:a="http://foo.com/abc"
exclude-result-prefixes="a"
>
<xsl:output method="xml" indent="yes"/>
<xsl:template match="@* | node()">
<xsl:copy>
<xsl:apply-templates select="@* | node()" />
</xsl:copy>
</xsl:template>
<xsl:template match="a:* | @a:*" />
</xsl:stylesheet>
先感谢您!
成功通过命名空间进行 XSLT 过滤的 JAVA 程序:
import java.io.*;
import org.w3c.dom.*; // XML DOM
import javax.xml.parsers.*; // DocumentBuilder, etc
import javax.xml.transform.*; // Transformer, etc
import javax.xml.transform.stream.*; // StreamResult, StreamSource, etc
import javax.xml.transform.dom.DOMSource;
public class Test {
public static void main(String[] args) {
new Test().testZoo();
}
public void testZoo () {
String zooXml = Test.readXmlFile ("zoo.xml");
if (zooXml == null)
return;
try {
// Create a new document builder factory, and make sure it[s namespace-aware
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
dbf.setNamespaceAware(true);
DocumentBuilder docBuilder = dbf.newDocumentBuilder ();
// Read XFDD input string into DOM
Document xfddDoc =
docBuilder.parse(new StringBufferInputStream (zooXml));
// Filter out all elements in "http://foo.com/abc" namespace
StreamSource styleSource = new StreamSource (new File ("zoo.xsl"));
Transformer transformer =
TransformerFactory.newInstance().newTransformer (styleSource);
// Convert final DOM back to String
StringWriter buffer = new StringWriter ();
transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); // Remember: we want to insert this XML as a subnode
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.transform(new DOMSource(xfddDoc), new StreamResult (buffer));
String translatedXml = buffer.toString();
}
catch (Exception e) {
System.out.println ("convertTransactionData error: " + e.getMessage());
e.printStackTrace ();
}
}