簡體   English   中英

從單個XSLT(Java)創建兩個XML文件

[英]Create two XML files from a single XSLT (Java)

我有一個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();

我怎樣才能實現自己想要的?

如果您使用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>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM