从单个XSLT(Java)创建两个XML文件

时间:2016-06-28 20:31:10

标签: java xml xslt

我有一个XSLT文件,我想用它来创建两个单独的XML文件/字符串。问题是我无法使用相同的模板匹配。

如果我有这个:

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

    <xsl:output method="xml" indent="yes"/>

    <xsl:template match="Frame/AAA">
        <xsl:for-each select=".">
            <Frame xmlns="MyNamespace.com">
                <BBB>
                    <!-- Stuff here -->
                </BBB>
            </Frame>
        </xsl:for-each>
     </xsl:template>

    <xsl:template match="Frame/AAA">
        <xsl:for-each select=".">
            <Frame xmlns="MyNamespace.com">
                <WWW>
                    <!-- Stuff here -->
                </WWW>
            </Frame>
        </xsl:for-each>
     </xsl:template>

</xsl:stylesheet>

XML文件:

<Frame>
    <AAA>
        <!-- Stuff here -->
    </AAA>
<Frame>

所以我想使用这两个模板并创建两个XML文件。但是,不允许使用两个相同的模板,因为它不知道在哪里查看。

这是我用来创建XML文件的Java代码:

// Get stylesheet (xslt) and xml data file
File stylesheet = new File(xsltFilepath);
InputSource inputSource = new InputSource(new ByteArrayInputStream(xmlString.getBytes()));

// Turn data file into document
Document document = DocumentBuilderFactory.newInstance()
        .newDocumentBuilder().parse(inputSource);

// Hold XML markup
StreamSource stylesource = new StreamSource(stylesheet);
// Turn source into a transformer object
Transformer transformer = TransformerFactory.newInstance().newTransformer(stylesource);
// Convert to a string
StringWriter stringWriter = new StringWriter();
transformer.transform(new DOMSource(document), new StreamResult(stringWriter));

// Return the string
return tringWriter.toString();

我如何实现我的目标?

1 个答案:

答案 0 :(得分:1)

如果您使用XSLT 2.0和模式,您可以使用例如

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

    <xsl:output method="xml" indent="yes"/>

    <xsl:template match="/">
       <xsl:apply-templates/>
       <xsl:apply-templates mode="m2"/>
    </xsl:template>

    <xsl:template match="Frame/AAA">

            <Frame xmlns="MyNamespace.com">
                <BBB>
                    <!-- Stuff here -->
                </BBB>
            </Frame>

     </xsl:template>

    <xsl:template match="Frame/AAA" mode="m2">
        <xsl:result-document href="result2.xml">
            <Frame xmlns="MyNamespace.com">
                <WWW>
                    <!-- Stuff here -->
                </WWW>
            </Frame>
        </xsl:result-document>
     </xsl:template>

</xsl:stylesheet>
相关问题