繁体   English   中英

从一堆xml文件中的特定正则表达式模式的搜索结果中获取xpath

[英]Get xpath from search result of a specific regex pattern in a bunch of xml files

我有许多XML文件,而且我必须在这些文件中搜索一个字符串(详细来说,这将是一个不太复杂的正则表达式)。

结果,我想获得字符串所在节点的xpath,即:

pattern = /home|house/

files: file1.xml, file2.xml etc

结果:

"home" in file1.xml, xpath: //root/cars/car[2]
"house" in file2.xml, xpath: //root[1]/elemA[2][@attribute1='first']

我怎样才能做到这一点? 我可以使用PHP,python,Javascript,VIM插件(因为我已经使用过这些插件)

搜索:

 //*[contains('home') or contains('house')]

在PHP中:

使用DOMDocument和DOMXPath,然后在结果匹配项上调用DOMNode::getNodePath()

如果您实际上需要正则表达式而不是之前的匹配项,则php的DOMDocument仅具有XPATH 1.0函数,但是您可以通过使用DOMXPath::registerPhpFunctions添加用户定义的函数来向DOMXPath添加功能。

快速整理一些东西而无需太多错误处理:

function xpathregexmatch($nodelist,$regex){
        foreach($nodelist as $node){
                if( $node instanceof DOMText && preg_match($regex,$node->nodeValue)) return true;
        }
        return false;
}

foreach(glob('*.xml') as $file){
        $d = new DOMDocument();
        $d->load($file);
        $x = new DOMXPath($d);
        $x->registerNamespace("php", "http://php.net/xpath");
        $x->registerPHPFunctions('xpathregexmatch');
        $matches = $x->query('//*[php:function("xpathregexmatch",text(),"/house|home/")]');
        if($matches->length){
                foreach($matches as $node){
                        echo $file. ':'.$node->getNodePath().PHP_EOL;
                }
        }
}

在PHP中: glob XML文件,对所有节点使用xpath ,对其所有文本进行preg_match_all ,如果匹配,则使用getNodePath()获取节点的xpath并将其输出:

$pattern = '/home|house|guide/iu';

foreach (glob('data/*.xml') as $file)
{
    foreach (simplexml_load_file($file)->xpath('//*') as $node)
    {
        if (!preg_match_all($pattern, $node, $matches)) continue;

        printf(
            "\"%s\" in %s, xpath: %s\n", implode('", "', $matches[0]),
            basename($file), dom_import_simplexml($node)->getNodePath()
        );
    }
}

结果(示例):

"Guide" in iana-charsets-2013-03-05.xml, xpath: /*/*[7]/*[158]/*[4]
"Guide" in iana-charsets-2013-03-05.xml, xpath: /*/*[7]/*[224]/*[2]
"Guide" in iana-charsets-2013-03-05.xml, xpath: /*/*[7]/*[224]/*[4]
"guide" in rdf-dmoz.xml, xpath: /*/*[4]/d:Description
"guide" in rdf-dmoz.xml, xpath: /*/*[5]/d:Description

顺便问一句。

php simplexml:

$xml=simplexml_load_string("file1.xml");
foreach ($xml->cars->car[2] as $car) {
    // do sth with $car
}

有关更多信息,请更具体地回答您的问题。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM