douyingyu5573 2013-03-03 17:49
浏览 32
已采纳

PHP在XML文件中更改xmlns

I have xml with the following structure:

<?xml version="1.0"?>
<ONIXMessage xmlns="http://test.com/test">
 ...data...
</ONIXMessage>

I need to change xmlns attribute with my own value. How can I do it? Preferably with DOMDocument class.

  • 写回答

1条回答 默认 最新

  • dptn69182 2013-03-04 01:30
    关注

    I need to change xmlns attribute with my own value. How can I do it? Preferably with DOMDocument class.

    This by design is not possible. Every DOMDocument has a single root/document element.

    In your example XML that root element is:

    {http://test.com/test}ONIXMessage
    

    I write the element name as an expanded-name with the convention to put the namespace URI in front enclosed in angle brackets.

    Writing the element name in a form that shows it's entire expanded-name also demonstrates that you do not only want to change the value of an attribute here, but you want to change the namespace URI of a specific element. So you want to change the element name. And probably also any child element name it contains if the child is in the same namespace.

    As the xmlns attribute only reflects the namespace URI of the element itself, you can not change it. Once it is set in DOMDocument, you can not change it.

    You can replace the whole element, but the namespace of the children is not changed either then. Here an example with an XML similar to yours with only textnode children (which aren't namespaced):

    $xml = <<<EOD
    <?xml version="1.0"?>
    <ONIXMessage xmlns="uri:old">
     ...data...
    </ONIXMessage>
    EOD;
    
    $doc = new DOMDocument();
    $doc->loadXML($xml);
    $newNode = $doc->createElementNS('uri:new', $doc->documentElement->tagName);
    $oldNode = $doc->replaceChild($newNode, $doc->documentElement);
    
    foreach(iterator_to_array($oldNode->childNodes, true) as $child) {
        $doc->documentElement->appendChild($child);
    }
    

    Resulting XML output is:

    <?xml version="1.0"?>
    <ONIXMessage xmlns="uri:new">
     ...data...
    </ONIXMessage>
    

    Changing the input XML now to something that contains children like

    <?xml version="1.0"?>
    <ONIXMessage xmlns="uri:old">
       <data>
         ...data...
       </data>
    </ONIXMessage>
    

    Will then create the following output, take note of the old namespace URI that pops up now again:

    <?xml version="1.0"?>
    <ONIXMessage xmlns="uri:new">
       <default:data xmlns:default="uri:old">
         ...data...
       </default:data>
    </ONIXMessage>
    

    As you can see DOMDocument does not provide a functionality to replace namespace URIs for existing elements out of the box. But hopefully with the information provided in this answer so far it is more clear why exactly it is not possible to change that attributes value if it already exists.

    The expat based parser in the libxml based PHP extension does allow to "change" existing attribute values regardless if it is an xmlns* attribute or not - because it just parses the data and you can process it on the fly with it.

    A working example is:

    $xml = <<<EOD
    <?xml version="1.0" encoding="utf-8"?>
    <ONIXMessage xmlns="uri:old">
      <data>
        ...data...
      </data>
    </ONIXMessage>
    EOD;
    
    $uriReplace = [
        'uri:old' => 'uri:new',
    ];
    
    $parser = xml_parser_create('UTF-8');
    xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, 0);
    xml_set_default_handler($parser, function ($parser, $data) {
        echo $data;
    });
    xml_set_element_handler($parser, function ($parser, $name, $attribs) use ($xml, $uriReplace) {
        $selfClosing = '/>' === substr($xml, xml_get_current_byte_index($parser), 2);
        echo '<', $name;
        foreach ($attribs as $name => $value) {
            if (substr($name, 0, 5) === 'xmlns' && isset($uriReplace[$value])) {
                $value = $uriReplace[$value];
            }
            printf(' %s="%s"', $name, htmlspecialchars($value, ENT_COMPAT | ENT_XML1));
        }
        echo $selfClosing ? '/>' : '>';
    }, function ($parser, $name) use ($xml) {
        $selfClosing = '/>' === substr($xml, xml_get_current_byte_index($parser) - 2, 2);
        if ($selfClosing) return;
        echo '</', $name, '>';
    });
    
    xml_parse($parser, $xml, true);
    xml_parser_free($parser);
    

    The output then has transparently changed the namespace URI from uri:old to uri:new:

    <ONIXMessage xmlns="uri:new">
       <data>
         ...data...
       </data>
    </ONIXMessage>
    

    As this example shows, each XML feature you make use of in your XML needs to be handled with the parser. For example the XML declaration is missing. However these can be added by implementing missing handler classbacks (e.g. for CDATA sections) or by outputting missing output (e.g. for the "missing" XML declaration). I hope this is helpful and shows you an alternative way on how to change even these values that are not intended to change.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 使用ESP8266连接阿里云出现问题
  • ¥15 被蓝屏搞吐了,有偿求帮解答,Ai回复直接拉黑
  • ¥15 BP神经网络控制倒立摆
  • ¥20 要这个数学建模编程的代码 并且能完整允许出来结果 完整的过程和数据的结果
  • ¥15 html5+css和javascript有人可以帮吗?图片要怎么插入代码里面啊
  • ¥30 Unity接入微信SDK 无法开启摄像头
  • ¥20 有偿 写代码 要用特定的软件anaconda 里的jvpyter 用python3写
  • ¥20 cad图纸,chx-3六轴码垛机器人
  • ¥15 移动摄像头专网需要解vlan
  • ¥20 access多表提取相同字段数据并合并