【发布时间】:2019-12-05 17:46:38
【问题描述】:
我有以下来自我必须使用的 API 的 xml 数据集:
<?xml version="1.0" encoding="utf-8"?>
<DataSet xmlns="http://examplesite.com/WebRes">
<xs:schema id="NewDataSet" xmlns="" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xs:element name="NewDataSet" msdata:IsDataSet="true" msdata:UseCurrentLocale="true">
<xs:complexType>
<xs:choice minOccurs="0" maxOccurs="unbounded">
<xs:element name="BuildingInfo">
<xs:complexType>
<xs:sequence>
<xs:element name="ID_Building" type="xs:int" minOccurs="0" />
<xs:element name="Name" type="xs:string" minOccurs="0" />
<xs:element name="Description" type="xs:string" minOccurs="0" />
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:choice>
</xs:complexType>
</xs:element>
</xs:schema>
<diffgr:diffgram xmlns:msdata="urn:schemas-microsoft-com:xml-msdata" xmlns:diffgr="urn:schemas-microsoft-com:xml-diffgram-v1">
<NewDataSet xmlns="">
<BuildingInfo diffgr:id="BuildingInfo1" msdata:rowOrder="0">
<ID_Building>333</ID_Building>
<Name>Example Building Name</Name>
<Description />
</BuildingInfo>
</NewDataSet>
<NewDataSet xmlns="">
<BuildingInfo diffgr:id="BuildingInfo1" msdata:rowOrder="0">
<ID_Building>334</ID_Building>
<Name>Example Building Name2</Name>
<Description />
</BuildingInfo>
</NewDataSet>
</diffgr:diffgram>
</DataSet>
这个问题是,如果我执行以下操作:
<?php $result = simplexml_load_string( $xml, 'SimpleXMLElement', 0, 'xs' );
echo ($result ? 'Valid XML' : 'Parse Error'), PHP_EOL;
print_r( $result );
结果是:
Parse Error
SimpleXMLElement Object
(
)
作为我使用的后备解决方案:
$p = xml_parser_create();
xml_parse_into_struct( $p, $xml, $result, $index );
xml_parser_free( $p );
哪个工作得很好。
另一个问题是,来自同一个 API 我也有这样的响应:
<?xml version="1.0" encoding="utf-8"?>
<ArrayOfRoomTypeBuildingsDetails xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="http://examplesite.com/WebRes">
<RoomTypeBuildingsDetails>
<ID_RoomType>123</ID_RoomType>
<RoomTypeName>Post Name</RoomTypeName>
<RoomTypeDescription>This is the description</RoomTypeDescription>
<GuestMax>2</GuestMax>
</RoomTypeBuildingsDetails>
</ArrayOfRoomTypeBuildingsDetails>
与simplexml_load_string() 函数完美配合。这意味着我使用 XML Parser 处理一些响应,而 simplexml_load_string() 用于其他不太容易维护的响应。
这里的问题是:有没有办法使用simplexml_load_string() 来解析这两种响应类型?还是我应该切换到 XML Parser 或 DOMDocument 或其他类似的库?
注意:从第一个 XML sn-p 开始,我只对从 NewDataSet 节点提取内容感兴趣。
如果您需要更多详细信息,请告诉我。任何帮助表示赞赏。
【问题讨论】:
标签: php xml xml-parsing