【问题标题】:Accessing elements of this xml访问此 xml 的元素
【发布时间】:2010-03-28 15:22:23
【问题描述】:
<wsdl:definitions targetNamespace="http://www.webserviceX.NET/">
<wsdl:types>
<s:schema elementFormDefault="qualified" targetNamespace="http://www.webserviceX.NET/">
<s:element name="ConversionRate">
<s:complexType>
<s:sequence>
<s:element minOccurs="1" maxOccurs="1" name="FromCurrency" type="tns:Currency"/>
<s:element minOccurs="1" maxOccurs="1" name="ToCurrency" type="tns:Currency"/>
</s:sequence>
</s:complexType>
</s:element>
<s:simpleType name="Currency">
<s:restriction base="s:string">
<s:enumeration value="AFA"/>
<s:enumeration value="ALL"/>
<s:enumeration value="DZD"/>
<s:enumeration value="ARS"/>

我正在尝试获取枚举中的所有元素,但似乎无法正确处理。这是家庭作业,因此请不要提供完整的解决方案,如果可能,请提供指导。

$feed = simplexml_load_file('http://www.webservicex.net/CurrencyConvertor.asmx?WSDL');

foreach($feed->simpleType as $val){
    $ns s = $val->children('http://www.webserviceX.NET/');
    echo $ns_s -> enumeration;
}

我做错了什么?

谢谢

【问题讨论】:

  • 只是评论,您发布的代码中有两个不同的变量,$ns s$ns_s
  • 抱歉,打错了,但还是同样的问题

标签: php xml web-services


【解决方案1】:

以下适用于 PHP 5.2:

$feedUrl = 'http://www.webservicex.net/CurrencyConvertor.asmx?WSDL';
$feed = simplexml_load_file($feedUrl);
$feed->registerXPathNamespace('s', 'http://www.w3.org/2001/XMLSchema');
foreach( $feed->xpath('//s:enumeration/@value') as $enumNode) {
    echo $enumNode, PHP_EOL;
}

print_r( $feed->getDocNamespaces() );

另一种方法是使用 DOM 扩展:

$feed = new DomDocument;
$feed->load('http://www.webservicex.net/CurrencyConvertor.asmx?WSDL');
$nodes = $feed->getElementsByTagNameNS(
    'http://www.w3.org/2001/XMLSchema', 
    'enumeration');

foreach( $nodes as $node ) {
    echo $node->getAttribute('value'), PHP_EOL;
}

【讨论】:

  • 是否可以提示我如何以我的方式进行操作,因为发布工作代码对我来说是有用的,因为我是学生意味着我不知道任何其他方式做真的是因为我缺乏经验,显然使用上述内容将被归类为作弊 - 理所当然:D
  • @csU 好吧,第一件事就是使用正确的命名空间。 s:enumaration 元素位于 XMLSchema 命名空间内。因此,在迭代 Feed Children 时,您希望将自己限制在这些范围内。
  • XML 在命名空间方面更胜一筹,因为它使用 lambda 继承模型,该模型与 C++、PHP、Java 等基于类的语言中使用的面向对象范围不兼容。
  • 所以 $ns_s = $val->children('w3.org/2001/XMLSchema');这是正确的命名空间吗?
  • @Csu 是的。如果您执行 $feed->getDocNamespaces() 您将看到哪些前缀注册到了哪个命名空间。但就像我说的,将 SimpleXML 与命名空间一起使用是一种痛苦。 Xpath 或 DOM非常更容易和可靠。
猜你喜欢
  • 2016-11-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多