How to determine XPaths passed when I request all child nodes?

I have an XML document that represents a directory structure. Directories are presented as <directory_name>, and files are presented as <file name="my_file.txt"/>.

For instance:

<xml>
    <home>
        <mysite>
            <www>
                <images>
                    <file name = "logo.gif" />
                </images>
                <file name = "index.html" />
                <file name = "about_us.html" />
            </www>
        </mysite>
    </home>
</xml>

I want to run an XPath query to get all the nodes <file>, but I also want to know the directory path for each file (i.e. the name of each parent node) - is there an easy way to do this with XPath, or will I need to do a recursive traversal of the XML tree after I parse it in PHP?

+3
source share
2 answers

The following XPath 2.0 expression :

   //file/concat(string-join(ancestor::*[parent::*]
                                   /concat(name(.), '/'),
                            ''),
                 @name, '&#xA;'
                 )

when evaluating the provided XML document :

<xml>
    <home>
        <mysite>
            <www>
                <images>
                    <file name="logo.gif"/>
                </images>
                <file name="index.html"/>
                <file name="about_us.html"/>
            </www>
        </mysite>
    </home>
</xml>

creates the desired, correct result :

home/mysite/www/images/logo.gif
 home/mysite/www/index.html
 home/mysite/www/about_us.html

If you cannot use XPath 2.0, it is not possible to get the desired result with only XPath 1.0 expression .

, XPath (, XSLT, #, php,...).

XSLT 1.0:

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

 <xsl:template match="file">
   <xsl:for-each select="ancestor::*[parent::*]">
     <xsl:value-of select="concat(name(),'/')"/>
   </xsl:for-each>
   <xsl:value-of select="concat(@name, '&#xA;')"/>
 </xsl:template>

 <xsl:template match="text()"/>
</xsl:stylesheet>

, XML-, :

home/mysite/www/images/logo.gif
home/mysite/www/index.html
home/mysite/www/about_us.html
+2

<?php 

$dom = new DOMDocument();
$dom->loadXML($xml);

$xpath = new DOMXPath($dom);
$arrNodes = $xpath->query('//file');
foreach($arrNodes as $node) {

$tmpNode = $node->parentNode;
$arrPath = array();
while ($tmpNode->parentNode) {
    $arrPath[] = $tmpNode->tagName;     
    $tmpNode = $tmpNode->parentNode;
}
unset($arrPath[count($arrPath)-1]); 
printf('%s/%s<BR>',implode('/',array_reverse($arrPath)),$node->getAttribute('name'));

}
0

Source: https://habr.com/ru/post/1781712/


All Articles