【问题标题】:How to add XML namespaces to parent elements in PHP如何在 PHP 中将 XML 命名空间添加到父元素
【发布时间】:2021-06-28 15:41:47
【问题描述】:

我想将命名空间添加到我的 XML 中的特定父(和子)元素,所以它看起来像这样:

<list xmlns:base="http://schemas.example.com/base">

   <base:customer>
      <base:name>John Doe 1</base:name>
      <base:address>Example 1</base:address>
      <base:taxnumber>10000000-000-00</base:taxnumber>
   </base:customer>

   <product>
      <name>Something</name>
      <price>45.00</price>
   </product>

</list>

我不知道如何将 base 命名空间添加到 customer 父元素。

这是我目前的代码:

header("Content-Type: application/xml");

$xml_string  = "<list xmlns:base='http://schemas.example.com/base'/>";

$xml = simplexml_load_string($xml_string);

$xml->addChild("customer");

$xml->customer->addChild("name", "John Doe 1", "http://schemas.example.com/base");
$xml->customer->addChild("address", "Example 1", "http://schemas.example.com/base");
$xml->customer->addChild("taxnumber", "10000000-000-00", "http://schemas.example.com/base");

$xml->addChild("product");

$xml->product->addChild("name", "Something");
$xml->product->addChild("price", "45.00");

print $xml->saveXML();

有了这个,唯一缺少的是 customer 元素的 base 命名空间。

【问题讨论】:

    标签: php xml namespaces simplexml parent


    【解决方案1】:

    两种方式:

    1. 将其用作默认命名空间

    &lt;list xmlns="http://schemas.example.com/base"&gt;

    1. 为元素添加前缀

    &lt;base:list xmlns:base="http://schemas.example.com/base"&gt;

    但是,这可能会导致访问元素的语法不同。解决这个问题的简单方法是将创建的元素存储到变量中。

    $xmlns_base = "http://schemas.example.com/base";
    
    $xml_string  = "<base:list xmlns:base='http://schemas.example.com/base'/>";
    
    $xml = simplexml_load_string($xml_string);
    
    $customer = $xml->addChild("base:customer", NULL, $xmlns_base);
    
    $customer->addChild("base:name", "John Doe 1", $xmlns_base);
    $customer->addChild("base:address", "Example 1", $xmlns_base);
    $customer->addChild("base:taxnumber", "10000000-000-00", $xmlns_base);
    
    // provide the empty namespace so it does not get added to the other namespace
    $product = $xml->addChild("product", "", "");
    
    $product->addChild("name", "Something");
    $product->addChild("price", "45.00");
    
    print $xml->saveXML();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-03-22
      • 1970-01-01
      • 2019-11-17
      • 2017-11-27
      • 1970-01-01
      • 1970-01-01
      • 2013-02-03
      相关资源
      最近更新 更多