Question

I am defining the elements of form in a simple XML structure like so:

<subtab id="page_background" label="Page Background" prefix="page">
   <input label="Background color" field="bgcolor" type="color"/>
   <input label="Background image" field="bgimage" type="image"/>
   <space />
 </subtab>
   etc.

I have large blocks containing absolutely identical information, e.g. the form fields for defining the background of the page, the content area, the top bar, and so on. This is making the XML file very cumbersome to work with and look through.

Is there a native XML "Copy + Paste" construct / command / statement that tells the XML parser - in my case, simpleXML - to look up the contents of a certain branch from another?

In pseudo-code:

<subtab id="content_background" copyFrom="../page_background">
<!-- sub-elements from "page_background" are magically copied here 
     by the parser -->
</subtab>
Was it helpful?

Solution

XML is just a format, so no copy command. XSLT can do that, but it's probably too complicated for your needs.

My advice: create a PHP function that adds your boilerplate elements. For example:

function default_elements(SimpleXMLElement $node)
{
    $default = array(
        'input' => array(
            array('label'=>"Background color", 'field'=>"bgcolor", 'type'=>"color"),
            array('label'=>"Background image", 'field'=>"bgimage", 'type'=>"image")
        ),
        'space' => array(
            array()
        )
    );

    foreach ($default as $name => $elements)
    {
        foreach ($elements as $attrs)
        {
            $new = $node->addChild($name);
            foreach ($attrs as $k => $v)
            {
                $new[$k] = $v;
            }
        }
    }
}

OTHER TIPS

You would create an SimpleXmlElement with the format and use clone, updating any changed attributes or sub tags each time.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top