从 xsd 数据结构解析 xml 数据?



我必须从xml文件中导入大约10 000个数据库条目,但是使用xsd文件数据结构,如何正确使用xsd文件导入xml数据?我使用PHP。

这是我的 xsd 架构:

<?xml version="1.0" encoding="UTF-8"?>
<!-- edited with XMLSpy v2010 rel. 3 (x64) (http://www.altova.com) -->
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" elementFormDefault="qualified" attributeFormDefault="unqualified">
<xs:element name="shopInformations">
<xs:annotation>
<xs:documentation>All products</xs:documentation>
</xs:annotation>
<xs:complexType>
<xs:sequence minOccurs="0" maxOccurs="unbounded">
<xs:element name="productInformation">
<xs:complexType>
<xs:sequence>
<xs:element name="title" type="xs:string"/>
<xs:element name="author" type="xs:string"/>
<xs:element name="productcode" type="xs:string" minOccurs="0"/>
<xs:element name="content"/>
<xs:element name="sections">
<xs:complexType>
<xs:sequence maxOccurs="unbounded">
<xs:element name="section">
<xs:complexType>
<xs:sequence>
<xs:element name="title"/>
</xs:sequence>
<xs:attribute name="id" type="xs:string" use="required"/>
</xs:complexType>
</xs:element>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:sequence>
<xs:attribute name="type" use="required">
<xs:simpleType>
<xs:restriction base="xs:string">
<xs:enumeration value="public"/>
<xs:enumeration value="reseller"/>
</xs:restriction>
</xs:simpleType>
</xs:attribute>
<xs:attribute name="version" type="xs:string" use="required"/>
<xs:attribute name="lang" use="required">
<xs:simpleType>
<xs:restriction base="xs:string">
<xs:enumeration value="en"/>
<xs:enumeration value="es"/>
</xs:restriction>
</xs:simpleType>
</xs:attribute>
</xs:complexType>
</xs:element>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:schema>

我的 xml 文件大约有 450MB,我无法打开它......

由于细节有点模糊,我不得不猜测很多,但是要读取这么大的文件,最好使用 XMLReader 来执行此操作。 XMLReader 允许您分段读取文件,而不是一次性读取整个文件。

以下代码显示了读取数据的简单方法,但由于我不得不从 XSD 创建一些测试数据 - 它可能并不完全正确。

<?php
error_reporting ( E_ALL );
ini_set ( 'display_errors', 1 );
$xml = new XMLReader;
$xml->open('t1.xml');
while( $xml->read() ) {
if($xml->name == "productInformation") {
$product = $xml->readOuterXML();
$prod = new SimpleXMLElement($product);
echo "title=".$prod->title.PHP_EOL;
echo "author=".$prod->author.PHP_EOL;
echo "productcode=".$prod->productcode.PHP_EOL;
echo "content=".$prod->content.PHP_EOL;
foreach ( $prod->sections->section as $section)    {
echo "section id=".$section['id'].PHP_EOL;
echo "section title=".$section->title.PHP_EOL;
}
echo PHP_EOL;
$xml->next();
}
}

如果要使用 SimpleXML 返回的值,则可能需要强制转换该值,因此$prod->title分配给字符串字段时需要(string)$prod->title

最新更新