Selecting parent nodes with XMLReader

前端 未结 3 1127
旧巷少年郎
旧巷少年郎 2020-12-20 00:16

I had to rewrite part of a programme to use XMLReader to select parts of an XML file for processing.

Take this simplified XML as an example:



        
3条回答
  •  猫巷女王i
    2020-12-20 00:50

    XMLReader can expand() the current node into a DOMNode. This will load only the node and its descendants into memory.

    After that, you can use a DOMXPath instance or convert the node into a SimpleXMLElement.

    $reader = new XMLReader();
    $reader->open('data:/text/xml,'.urlencode($xml));
    
    $dom = new DOMDocument();
    $xpath = new DOMXpath($dom);
    
    while($reader->read()) {
      if (
        $reader->nodeType == XMLReader::ELEMENT && 
        $reader->localName == 'bet'
      ) {
        $bet= $reader->expand($dom);
        if ($xpath->evaluate('count(selection[@selectionid = "52411062.1"]) > 0', $bet)) {
          var_dump($dom->saveXml($bet));
        }
      }
    }
    

    You will always have to decide which part to implement in XMLReader and which in DOM/SimpleXML. In XMLReader you will have to validate the nodes and maintain a state, but can avoid to load the data. At one point in the parsing the XML snippets will be small enough and you can use expand().

提交回复
热议问题