【问题标题】:creating multiple xml nodes with same namespaces in php在php中创建具有相同命名空间的多个xml节点
【发布时间】:2012-05-15 09:52:09
【问题描述】:

我有以下代码

    $dom = new DOMDocument('1.0', 'utf-8');        
    $headerNS = $dom->createElementNS('http://somenamespace', 'ttauth:authHeader');
    $accesuser = $dom->createElementNS('http://somenamespace', 'ttauth:Accessuser','aassdd');
    $accesscode = $dom->createElementNS('http://somenamespace', 'ttauth:Accesscode','aassdd');
    $headerNS->appendChild($accesuser);
    $headerNS->appendChild($accesscode);

    echo "<pre>";
    echo ($dom->saveXML($headerNS));
    echo "</pre>";

IT 将生成以下 xml 作为输出

<?xml version="1.0" ?>
<ttauth:authHeader xmlns:ttauth="http://somenamespace">
<ttauth:Accessuser>
    ApiUserFor136
</ttauth:Accessuser>
<ttauth:Accesscode>
    test1234
</ttauth:Accesscode>
</ttauth:authHeader>

但我想要以下输出

<ttauth:authHeader xmlns:ttauth="http://somenamespace">

  <ttauth:Accessuser xmlns:ttauth="http://somenamespace">
    aassdd
  </ttauth:Accessuser>

  <ttauth:Accesscode xmlns:ttauth="somenamespace">
    aassdd
  </ttauth:Accesscode>

</ttauth:authHeader>

看到 xmlns 不包含在根元素以外的元素中,但我希望 xmlns 包含在所有元素中我做错了什么吗??

【问题讨论】:

    标签: php xml domdocument xml-namespaces


    【解决方案1】:

    可能 PHP 解析器不会添加具有相同前缀“ttauth”的相同命名空间“http://somenamespace”的重命名,因为它是多余的。您显示的两个 xml(输出和预期)是等效的。如果您想确保拥有所需的命名空间属性,您应该使用 addAtribute - http://www.php.net/manual/en/domdocument.createattribute.php 手动添加它们。见以下代码sn -p:

    $domAttribute = $domDocument->createAttribute('xmlns:ttauth');
    $domAttribute->value = 'http://somenamespace';
    $accessuser->appendChild($domAttribute);
    

    希望对你有帮助

    【讨论】:

    • 这也有一个问题。当我将相同的属性附加到两个子节点时它不起作用:(
    • 这是正确的行为。即使内容相同,也应该为每个子节点创建不同的属性。
    【解决方案2】:

    而不是使用

    $accesuser = $dom->createElementNS('http://somenamespace', 'ttauth:Accessuser','aassdd');
    

    我用过

    $accesuser = $dom->createElement('http://somenamespace', 'ttauth:Accessuser','aassdd');
    

    然后

    $accesuser->setAttribute('xmlns:ttauth', ('http://somenamespace');
    

    它适用于任意数量的节点

    【讨论】:

      猜你喜欢
      • 2015-04-16
      • 2010-11-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多