For each in FOP xml

2019-09-08 06:15发布

问题:

I'm generating a PDF through Apache FOP, and since now things are going pretty well.

Now I need to loop through a list and display every element in it and to achieve this I'm using the command <xsl:for-each select="myObject/myList">, but when FOP begin to parse the XML I get this error:

2015-09-30 12:04:39,772 [http-nio-8080-exec-4] WARN  org.apache.fop.apps.FOUserAgent - Unknown formatting object "{http://www.w3.org/1999/XSL/Transform}for-each" encountered (a child of fo:root}. (See position 9:45)
java.lang.ClassCastException: org.apache.fop.fo.UnknownXMLObj cannot be cast to org.apache.fop.fo.pagination.Root
    at org.apache.fop.fo.pagination.AbstractPageSequence.getRoot(AbstractPageSequence.java:145)
    at org.apache.fop.fo.pagination.PageSequence.startOfNode(PageSequence.java:111)
    at org.apache.fop.fo.FOTreeBuilder$MainFOHandler.startElement(FOTreeBuilder.java:337)
    at org.apache.fop.fo.FOTreeBuilder.startElement(FOTreeBuilder.java:179)
    at org.apache.xalan.transformer.TransformerIdentityImpl.startElement(TransformerIdentityImpl.java:1072)
[...]

This is the structure of my XML:

<?xml version="1.0" encoding="utf-8"?>
<fo:root xmlns:fo="http://www.w3.org/1999/XSL/Format" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <fo:layout-master-set>
        <fo:simple-page-master master-name="A4-portrait"
            page-height="29.7cm" page-width="21.0cm" margin="1.5cm">
            <fo:region-body />
        </fo:simple-page-master>
    </fo:layout-master-set>
    <xsl:for-each select="myObject/myList">
        <fo:page-sequence master-reference="A4-portrait">
            <fo:flow flow-name="xsl-region-body" font-size="9">
                ## SOME STUFF ARE WRITTEN HERE ##
            </fo:flow>
        </fo:page-sequence>
    </xsl:for-each>
</fo:root>

I understood that a problem could be the fact that FOP only wants fo: elements. And if this is correct, how can I loop over my list?

回答1:

You need XSLT (or something that does the same job) to convert your XML into the FO vocabulary that FOP understands.

Your xsl:for-each will be understood by an XSLT processor. See 'Hello World with FOP' in the FOP Quick Start Guide at http://xmlgraphics.apache.org/fop/quickstartguide.html for a minimal example.

FOP can run the XSLT transformation as part of its processing, but you can also use a standalone XSLT processor such as Saxon to produce an FO file that you can then feed to FOP.