Pass xml document as parameter to xsl

余生颓废 提交于 2020-01-11 09:53:50

问题


I have read a lot of post and tried a lot of things but still can't get the xsl to find values in the parameter. I started with java's sun xalan and never got it working so I switched to saxon to no avail. I want to combine two xml docs into one with xls. Never are on a file system, this is for a web app that builds xml strings/ docs. I have tried passing an DTMAxisIterator, DomSource , Doc to Node set in xsl, string. It worked fine in NotePad++ with an xsl document() but I don't want to save the xml on the system.

XSL

<xsl:param name="RsXml" select="/"/>

<xsl:template match="/policy/vehicles">
<vehicle type="DP" type_code="DP"/>

        <xsl:for-each select="$RsXml/InsuranceSvcRs /com.csc_PolicyOrderCurrentCarrierInqRs/PersVeh">

            <vin>
                <xsl:value-of select="VehIdentificationNumber"/>
            </vin>
            <veh_year>
                <xsl:value-of select="ModelYear"/>
            </veh_year>
            <make>
                <xsl:value-of select="Manufacturer"/>
            </make>
            <model>   
                <xsl:value-of select="Model"/>
            </model>
            <costnew>               
                <xsl:value-of select="CostNewAmt/Amt"/>
            </costnew>
            <symbol>
                <xsl:value-of select="VehSymbolCd"/>
            </symbol>
            <wheregaraged></wheregaraged>
            <liabilityonly></liabilityonly>
            <collision></collision>
            <comprehensive></comprehensive>
            <rentalreimbursement></rentalreimbursement>
            <towing></towing>
            <altered></altered>
            <title></title>
            <enginesize>
                <xsl:value-of select="NumCylinders"/>
            </enginesize>
            <trailertype/>
            <trtonnage/>
            <mctype/>
            <mcenginecc/>
            <vehicleuse></vehicleuse>
            <mhawnings></mhawnings>
            <vseat15></vseat15>
            <vseat15text/>
            <extraequipment></extraequipment>
            <mcsidecar></mcsidecar>
            <atvwheels/>
            <damage/>
            <endorsements/>
            <avtotal/>
            <v_underwriting>
                <altered></altered>
                <alteredlist/>
                <alteredexplain/>
                <businessuse></businessuse>
                <haulstudents></haulstudents>
                <pulltrailers></pulltrailers>
                <trailerendorsement/>
            </v_underwriting>
            <driverid></driverid>
            <gen_classcode></gen_classcode>
            <classcode></classcode>
            <primary_veh></primary_veh>
            <rates>
                <bi></bi>
                <pd></pd>
                <med></med>
                <ubi></ubi>
                <upd></upd>
                <comp></comp>
                <coll></coll>
                <comm></comm>
                <rr></rr>
                <tl></tl>
            </rates>
            <xferdis></xferdis>
            <atv_young_dr></atv_young_dr>
            <mrcd_date/>
            <hasdamage></hasdamage>
            <comp_symbol></comp_symbol>
            <str_legal></str_legal>
            <addresses/>


        </xsl:for-each>     
<xsl:apply-templates/>

XML One

           <?xml version="1.0" encoding="UTF-8"?>
               <policy id="1735">       
              <vehicles>        
              </vehicles>
                </policy>

XML Two

      <ACORD>
     <InsuranceSvcRs>
      <com.csc_PolicyOrderCurrentCarrierInqRs>
        <PersVeh id="001">
            <ItemIdInfo>
                <InsurerId>001</InsurerId>
            </ItemIdInfo>
            <Manufacturer>FORD</Manufacturer>
            <Model>WINDSTAR</Model>
            <ModelYear>1999</ModelYear>
            <VehBodyTypeCd>ES</VehBodyTypeCd>
            <CostNewAmt>
                <Amt>23660</Amt>
            </CostNewAmt>
            <NumDaysDrivenPerWeek />
            <EstimatedAnnualDistance>
                <NumUnits />
                <UnitMeasurementCd />
            </EstimatedAnnualDistance>
            <FullTermAmt>
                <Amt />
            </FullTermAmt>
            <TerritoryCd />
            <VehIdentificationNumber>1</VehIdentificationNumber>
            <NumCylinders>6</NumCylinders>
            <VehSymbolCd />
            <AntiLockBrakeCd>4-WHEEL STD</AntiLockBrakeCd>
            <DaytimeRunningLightInd />
            <DistanceOneWay>
                <NumUnits />
                <UnitMeasurementCd>MI</UnitMeasurementCd>
            </DistanceOneWay>
            <AntiTheftDeviceCd>PASS-KEY</AntiTheftDeviceCd>
            <VehPerformanceCd />
            <VehUseCd />
            <AirBagTypeCd>BOTH</AirBagTypeCd>
            <com.csc_VehBodyTypeFreeformInd />
        </PersVeh>          
    </com.csc_PolicyOrderCurrentCarrierInqRs>
    </InsuranceSvcRs>
   </ACORD>

Class

    public String transformResultXML(String xmlSource, Templates xsl,String policyXml ) {
       String result = "";  

    try {

          StringWriter writer = new StringWriter();
          StringReader reader2 = new StringReader(policyXml);

          XmlHelper xh = new XmlHelper();
          Document xmlSrc = xh.loadDoc(xmlSource);
          DOMSource source = new DOMSource(xmlSrc);


          ByteArrayInputStream byteStream = new  ByteArrayInputStream(xmlSource.getBytes());
          StringReader reader = new StringReader(xmlSource);
          SAXSource source2 = new SAXSource(new XMLFilterImpl(), new  InputSource(reader));

          TransformerFactory transFact = new com.icl.saxon.TransformerFactoryImpl();

          Transformer transformer = transFact.newTransformer();

          transformer.setParameter("RsXml",source2);
         // transformer.setParameter("RsXml",xmlSrc);
          transformer.setOutputProperty(OutputKeys.INDENT, "yes");
          transformer.transform(new javax.xml.transform.stream.StreamSource(reader2),
                  new javax.xml.transform.stream.StreamResult(writer));
          result = writer.toString();
          System.out.println(result);

    } catch( Exception e ) {
        e.printStackTrace();
    }

    return result;
}   

回答1:


I was able to get it work with Saxon see below code. I think the key was the document.getDocumentElement() as parm

      public String transformResultXML(String xmlSource, Templates xsl,String policyXml )    {
       String result = "";  

    try {

          StringWriter writer = new StringWriter();
          StringReader reader2 = new StringReader(policyXml);

          DocumentBuilderFactory dfactory =
                  DocumentBuilderFactory.newInstance( "com.icl.saxon.om.DocumentBuilderFactoryImpl",null);

          dfactory.setNamespaceAware(true);

          DocumentBuilder docBuilder = dfactory.newDocumentBuilder();

          org.w3c.dom.Document document = docBuilder.parse(new InputSource(new StringReader(xmlSource)));

          Transformer transformer = xsl.newTransformer();

          transformer.setParameter("RsXml", document.getDocumentElement());

          transformer.setOutputProperty(OutputKeys.INDENT, "yes");
          transformer.transform(new javax.xml.transform.stream.StreamSource(reader2),
                  new javax.xml.transform.stream.StreamResult(writer));
          result = writer.toString();
          System.out.println(result);

    } catch( Exception e ) {
        e.printStackTrace();
    }

XSL snippet

    <xsl:param name="RsXml" />

<xsl:template match="/policy/vehicles">


        <xsl:for-each select="$RsXml/InsuranceSvcRs/com.csc_PolicyOrderCurrentCarrierInqRs/PersVeh">



回答2:


When you use the JAXP interface, the values you can supply for parameters are not defined in the API specification, and Saxon's support may differ from Xalan's. Generally I think you will find that Saxon's s9api interface is much easier to use. Certainly its methods for supplying parameters are strongly typed and it's much clearer what you can supply. If you want to supply a node, it should be an instance of XdmNode, and you can create an XdmNode by parsing lexical XML using a s9api DocumentBuilder, or by wrapping a DOM Node.




回答3:


When you pass a parameter to an XSL stylesheet, the value is a string and is not parsed into a DOM. This is not currently possible in standard XSLT. There may be an extension that will do this but I'm not aware of one.



来源:https://stackoverflow.com/questions/13381698/pass-xml-document-as-parameter-to-xsl

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!