首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >SimpleXMLElement addAttribute名称空间语法

SimpleXMLElement addAttribute名称空间语法
EN

Stack Overflow用户
提问于 2017-04-23 00:00:46
回答 1查看 1.9K关注 0票数 2

我第一次使用SimpleXMLElement,需要在XML中生成一行如下所示:

代码语言:javascript
复制
<Product xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">

我以前没有在名称空间中使用过addAttribute,在这里也不能正确使用语法--我已经从以下几个方面开始:

代码语言:javascript
复制
$node = new SimpleXMLElement('< Product ></Product >');
$node->addAttribute("xmlns:", "xsd:", 'http://www.w3.org/2001/XMLSchema-instance'); 

但无法解决如何纠正这一点,以生成适当的语法来生成所需的输出?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2017-04-23 00:22:51

解决方案1:在前缀中添加前缀

代码语言:javascript
复制
<?php
$node = new SimpleXMLElement('<Product/>');
$node->addAttribute("xmlns:xmlns:xsi", 'http://www.w3.org/2001/XMLSchema-instance');
$node->addAttribute("xmlns:xmlns:xsd", 'http://www.w3.org/2001/XMLSchema');
echo $node->asXML();

产出:

代码语言:javascript
复制
<?xml version="1.0"?>
<Product xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"/>

注意:这是一种解决方法,实际上没有为属性设置名称空间,但如果要回显/保存以提交结果,则足够了。

解决方案2:将命名空间直接放在SimpleXMLElement构造函数

代码语言:javascript
复制
<?php
$node = new SimpleXMLElement('<Product xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"/>');
echo $node->asXML();

输出与解决方案1相同。

解决方案3(添加附加属性)

代码语言:javascript
复制
<?php
$node = new SimpleXMLElement('<Product/>');
$node->addAttribute("xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance", "xmlns");
$node->addAttribute("xmlns:xsd", 'http://www.w3.org/2001/XMLSchema', "xmlns");
echo $node->asXML();

输出添加额外的xmlns:xmlns="xmlns"

代码语言:javascript
复制
<?xml version="1.0"?>
<Product xmlns:xmlns="xmlns" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"/>
票数 8
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/43565945

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档