我想在我的 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();
这样,唯一缺少的是客户元素的基本命名空间。
答案 0 :(得分:2)
两种方式:
<list xmlns="http://schemas.example.com/base">
<base:list xmlns:base="http://schemas.example.com/base">
然而,这可能会导致访问元素的语法不同。解决这个问题的简单方法是将创建的元素存储到变量中。
$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();