【问题标题】:Adding namespace to XML将命名空间添加到 XML
【发布时间】:2014-11-04 09:14:11
【问题描述】:

我正在使用 PHP 为我们的一个客户创建 XML 响应,其中包含名称空间 URL。我期待的输出如下,

<?xml version="1.0" encoding="UTF-8"?>
<ns3:userResponse xmlns:ns3="http://www.w3.org/2001/XMLSchema-instance" xmlns:ns2="http://www.w3.org/2001/XMLSchema">
   <Content>
      <field1>fieldvalue1</field1>
   </Content>
</ns3:userResponse>

但是通过使用下面的代码,

<?php
// create a new XML document
$doc = new DomDocument('1.0', 'UTF-8');

// create root node
$root = $doc->createElementNS('http://www.w3.org/2001/XMLSchema-instance', 'ns3:userResponse');
$root = $doc->appendChild($root);

$root->setAttributeNS('http://www.w3.org/2001/XMLSchema-instance', 'ns1:schemaLocation','');
$root->setAttributeNS('http://www.w3.org/2001/XMLSchema', 'ns2:schemaLocation','');

// add node for each row
$occ = $doc->createElement('Content');
$occ = $root->appendChild($occ);


$child = $doc->createElement("field1");
$child = $occ->appendChild($child);

$value = $doc->createTextNode('fieldvalue1');
$value = $child->appendChild($value);


// get completed xml document
$xml_string = $doc->saveXML();

echo $xml_string;

演示: 演示在这里,http://codepad.org/11W9dLU9

这里的问题是,第三个属性是setAttributeNS PHP 函数的强制属性。所以,我得到的输出是,

<?xml version="1.0" encoding="UTF-8"?>
<ns3:userResponse xmlns:ns3="http://www.w3.org/2001/XMLSchema-instance" xmlns:ns2="http://www.w3.org/2001/XMLSchema" ns3:schemaLocation="" ns2:schemaLocation="">
   <Content>
      <field1>fieldvalue1</field1>
   </Content>
</ns3:userResponse>

那么,无论如何要删除带有空值的ns3:schemaLocationns2:schemaLocation?我用谷歌搜索了很多,但找不到任何有用的答案。

对此的任何想法都会很棒。请帮忙。

【问题讨论】:

标签: php xml domdocument


【解决方案1】:

你创建这个属性:

$root->setAttributeNS('http://www.w3.org/2001/XMLSchema-instance', 'ns1:schemaLocation','');
$root->setAttributeNS('http://www.w3.org/2001/XMLSchema', 'ns2:schemaLocation','');

删除此行,它们将被删除。

如果你想添加一些xmlns而不在代码中使用它是:

$attr_ns = $doc->createAttributeNS( 'http://www.w3.org/2001/XMLSchema', 'ns2:attr' );

阅读此评论:http://php.net/manual/pl/domdocument.createattributens.php#98210

【讨论】:

  • 在下面添加这一行:$root = $doc->appendChild($root);在你的代码中
猜你喜欢
  • 1970-01-01
  • 2023-03-24
  • 2017-09-21
  • 2013-09-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-06-11
  • 1970-01-01
相关资源
最近更新 更多