我想在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元素的基础名称空间。
两种方式:
- 将其用作默认命名空间
<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();