Create XML with xmlns:xlink attribute in a node

前端 未结 1 680
抹茶落季
抹茶落季 2021-01-06 23:20

i\'m trying to add generate an output like this:



        
相关标签:
1条回答
  • 2021-01-06 23:50

    The solution I've come up with is rather straight forward:

    Because

    $mets->addAttribute("xlink:someName", "", "http://www.w3.org/1999/xlink");
    

    will always add two attributes - one for the namespace declaration (xmlns:xlink) and then the attribute you actually add (xlink:someName) - all you need to do is then to remove the unwanted added attribute and the prefix namespace attribute will remain:

    unset($mets->attributes('xlink', true)['someName']);
    

    Full example:

    $mets = new SimpleXMLElement('<mets></mets>');
    $mets->addAttribute("xlink:someName", "", "http://www.w3.org/1999/xlink");
    unset($mets->attributes('xlink', true)['someName']);
    echo $mets->asXML();
    

    Output:

    <?xml version="1.0"?>
    <mets xmlns:xlink="http://www.w3.org/1999/xlink"/>
    

    However this normally should not be necessary. You either need to use the namespace for something - then simplexml will add it when needed - or you don't need it, then there is no need to add it.

    XML itself has no requirement at all to declare a namespace which is not used. Therefore you likely can leave it out as well or you only need to add it where you need to add it, e.g. the specific xlink element / attribute later on.

    Any XML parser that supports namespaces will support any well-formed XML+Namspaces document, so there should really be no reason to worry whether or not the root element has that declaration and with which prefix. Simplexml just takes care of that, just add the xlink attribute where you need it. Example:

    $mets = new SimpleXMLElement('<mets></mets>');
    $child = $mets->addChild('child');
    $child->addAttribute('xlink:href', 'child.xml', 'http://www.w3.org/1999/xlink');
    $child = $child->addChild('child');
    $child->addAttribute('xlink:href', 'child.xml', 'http://www.w3.org/1999/xlink');
    echo $mets->asXML();
    

    Output:

    <?xml version="1.0"?>
    <mets>
      <child xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="child.xml">
        <child xlink:href="child.xml"/>
      </child>
    </mets>
    
    0 讨论(0)
提交回复
热议问题