【问题标题】:Using TransformToXml on SimpleXMLElements returned by an xpath selection在 xpath 选择返回的 SimpleXMLElements 上使用 TransformToXml
【发布时间】:2018-12-17 19:06:03
【问题描述】:

我希望能够使用 XSLT 来处理 XPath 选择的 XML sn-p。当我传递$xmlSnippet 时,它的行为就好像我传递了整个$xml。我如何告诉处理器处理 sn-p 而不是整个文件?

XML

<?xml version="1.0" encoding="UTF-16"?>
<FMPReport link="Summary.xml" creationTime="12:10:13 pm" creationDate="30/10/2015" type="Report" version="14.0.3">
<File name="assets.fmp12" path="server.com">
<CustomFunctionCatalog>
    <CustomFunction id="1" functionArity="1" visible="True" parameters="pageID" name="!filemakerstandards.org">
        <Calculation><![CDATA["http://filemakerstandards.org/pages/viewpage.action?pageId=" & pageID]]></Calculation>
    </CustomFunction>
    <CustomFunction id="2" functionArity="2" visible="True" parameters="name;value" name="#">
        <Calculation><![CDATA['example 2']]></Calculation>
    </CustomFunction>
</CustomFunctionCatalog>
</File>
</FMPReport>

XSL

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
    <xsl:output method="html" encoding="UTF-8"/>
    <xsl:template match="/">
        <xsl:value-of select="name(child::*[1])"/>
        </xsl:template>
    <xsl:template match="text()" />
</xsl:stylesheet>

PHP

function displayCustomFunction($customFunctionId) {
    LIBXML_NOWARNING;
    LIBXML_NOCDATA;
    LIBXML_PARSEHUGE;
    LIBXML_BIGLINES;
    LIBXML_COMPACT;
    $filePath = 'xml/abc';
    $xslPath = 'xsl/abc';
    $xml = simplexml_load_file( $filePath, 'SimpleXMLElement');
    // ->xpath returns an array, in this case, an array of one item. array()[0] will be a SimpleXMLElement
    $xmlSnippet  = $xml->xpath('File/CustomFunctionCatalog/CustomFunction[@id=\''.$customFunctionId.'\']')[0];
    $xsl = simplexml_load_file( $xslPath, 'SimpleXMLElement');
    $xslt = new XSLTProcessor();
    $xslt->importStylesheet($xsl);
    $xslt->transformToXml($xml);        // returns 'FMPReport'
    $xslt->transformToXml($xmlSnippet); // returns 'FMPReport'. Expecting 'Calculation'
}

【问题讨论】:

    标签: php xslt simplexml


    【解决方案1】:

    没有得到任何答案 我只是通过构建一个字符串并将其加载为 XML 来解决这个问题。

    $cfString = '';
    foreach( $cfArray as $item){
        $cfString .= $item->asXML();
    }
    
    $cfXml = <<<XML
    <?xml version='1.0'?> 
    <FMPReport>
    <File name="{$fileName[0]}">
    <CustomFunctionCatalog>
    $cfString
    </CustomFunctionCatalog>
    </File>
    </FMPReport>
    XML;
    
    $xml  = simplexml_load_string($cfXml);
    

    然后用 XSLT 处理。

    【讨论】:

    • 我在使用 php7.3 >3 年后遇到同样的问题,并且将使用相同的解决方案。
    猜你喜欢
    • 1970-01-01
    • 2019-12-30
    • 1970-01-01
    • 2019-01-07
    • 2016-12-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-10
    相关资源
    最近更新 更多