使用PHP解析XML命名空间

时间:2012-06-07 01:50:17

标签: php xml-parsing simplexml

我一直在靠墙试图解析下面第一个xs:序列下的项目(从AssetID开始):

<Response>
  <xs:schema id="Response" xmlns="" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
    <xs:element name="Response" msdata:IsDataSet="true" msdata:UseCurrentLocale="true">
      <xs:complexType>
        <xs:choice minOccurs="0" maxOccurs="unbounded">
          <xs:element name="Server">
            <xs:complexType>
              <xs:sequence>
                <xs:element name="AssetID" type="xs:int" minOccurs="0" />
                <xs:element name="Asset_x0020_Number" type="xs:int" minOccurs="0" />
                <xs:element name="Asset_x0020_Name" type="xs:string" minOccurs="0" />
                <xs:element name="Tag" type="xs:string" minOccurs="0" />
                <xs:element name="Server_x0020_Material" type="xs:string" minOccurs="0" />
                <xs:element name="Cabinet_x0020_Name" type="xs:string" minOccurs="0" />
                <xs:element name="Server_x0020_Project_x0020_Purpose" type="xs:string" minOccurs="0" />
                <xs:element name="Tranche_x0020_Number" type="xs:int" minOccurs="0" />
                <xs:element name="Strategy" type="xs:string" minOccurs="0" />
                <xs:element name="Total_x0020_System_x0020_U_x0020_Height" type="xs:int" minOccurs="0" />
                <xs:element name="Cabinet_x0020_U_x0020_Number" type="xs:int" minOccurs="0" />
                <xs:element name="Mounting_x0020_Direction" type="xs:string" minOccurs="0" />
                <xs:element name="Serial_x0020_Number" type="xs:string" minOccurs="0" />
                <xs:element name="Purchase_x0020_Price" type="xs:decimal" minOccurs="0" />
                <xs:element name="Location_x0020_Group" type="xs:string" minOccurs="0" />
                <xs:element name="Row" type="xs:string" minOccurs="0" />
                <xs:element name="Column" type="xs:string" minOccurs="0" />
                <xs:element name="Rotation" type="xs:int" minOccurs="0" />
                <xs:element name="AssetOperationalStatus" type="xs:string" minOccurs="0" />
                <xs:element name="Discovered" type="xs:boolean" minOccurs="0" />
                <xs:element name="Power_x0020_State" type="xs:string" minOccurs="0" />
              </xs:sequence>
            </xs:complexType>
          </xs:element>
          <xs:element name="Strategy">
            <xs:complexType>
            [...continues on...]

我一直在尝试使用PHP的SimpleXMLElement,但我无法弄清楚如何只隔离那20行。 我只需要一个元素名称数组,例如:

{"AssetID", "Asset_x0020_Number","Asset_x0020_Tag","Tag", ... ,"Power_x0020_State"}

1 个答案:

答案 0 :(得分:2)

以下是显示每个xs:element

的“name”属性的示例
$xml = simplexml_load_string($xmlString);
$namespaces = $xml->getNameSpaces(true);
$xs = $xml->children($namespaces['xs']);

foreach($xs->schema->element->complexType->choice->element->complexType->sequence->element as $element) {
    echo $element->attributes()->name.PHP_EOL;
}