PHP Xpath string to XML

1

I'm assailed by a doubt. I know that I can transform a string like:

<nodo1><nodo_1_hijo></nodo_1_hijo></nodo>

A xml with SimpleXMLElement.

But will it be possible to transform an xpath to xml like the following?:

//nodo1/nodo_1_hijo

And what is left like the example above?

    
asked by Makeyourmove 19.05.2017 в 01:18
source

2 answers

1

The XML path language ( Xpath ) was created for facilitate the search for elements within an XML tree :

  

The primary purpose of XPath is to address parts of an XML document

     

The main goal of XPath is to access parts of a document   XML

So it is not advisable to use a path xpath as a description of the structure of a document XML . That's why we use the DTD .

If you want to generate a% basic% co from a basic path XML you can use this small piece of code:

<pre><?php
function agregar_xml_desde_xpath($xpath, $dom) {
    $elementos = explode('/', $xpath);
    $actual = $dom;
    foreach ($elementos as $elemento) {
        if (!empty($elemento)) {
            $nuevo = $dom->createElement($elemento);
            $actual->appendChild($nuevo);
            $actual = $nuevo;
        }
    }
}

$dom = new DOMDocument();
agregar_xml_desde_xpath('//nodo1/nodo_1_hijo', $dom);
echo htmlspecialchars($dom->saveXML(null, LIBXML_NOEMPTYTAG));
?><pre>

The result obtained is:

<?xml version="1.0"?>
<nodo1><nodo_1_hijo></nodo_1_hijo></nodo1>

Keep in mind that it is a very simple implementation that only the node tree obtains. For more complex routes (using attributes, functions, etc.) the implementation could become complex.

    
answered by 22.05.2017 в 12:52
0

It's pretty easy with the xpath function that SimpleXMLElement has

It would be like this:

$obj = new SimpleXMLElement($xml);
$reg = $obj->xpath('//nodo1/nodo_1_hijo');
echo $reg[0]->saveXML();

In $ xml you should have the XML string. This should be correct, in your case right now it is not, since you open as node1, but you close as a node. Anyway, PHP itself will warn you of those errors.

In my code, as you will see, the only first record that matches the XPath you have indicated will be passed to XML. If you want to get all matches you should use foreach .

    
answered by 22.05.2017 в 10:31