0

私は多くの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プラグインを使用できます(すでにこれらを使用しているため)

4

3 に答える 3

3

探す:

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

PHPの場合:

DOMDocumentとDOMXPathを使用DOMNode::getNodePath()して、結果の一致を呼び出すだけです。

以前の一致の代わりに実際に正規表現が必要な場合、phpのDOMDocumentにはXPATH 1.0関数しかありませんが、次のユーザー定義関数を追加することでDOMXPathに機能を追加できます。DOMXPath::registerPhpFunctions

多くのエラー処理を行わずに、何かをすばやく作成します。

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;
                }
        }
}
于 2013-03-06T23:04:57.080 に答える
2

PHPglobの場合:XMLファイル、xpathすべてのノード、preg_match_allそれらのテキスト、および一致する場合は、ノードのxpathを取得しgetNodePath()て出力します。

$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

いい質問です。

于 2013-03-07T02:43:52.650 に答える
0

php simplexml:

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

詳細については、質問を具体的にお願いします。

于 2013-03-06T22:58:19.133 に答える