我使用简化的SQL编写简单的XML解析器。我有一个类似的东西
`<catalog>
<library><room id="1">
<book id="bk101">
<author>Gambardella, Matthew</author>
<title>XML Developer's Guide</title>
<genre>Computer</genre>
<price>44.95</price>
<publish_date>2000-10-01</publish_date>
<description>An in-depth look at creating applications
with XML.</description>
</book></room>
<room id="2">
<book id="bk102">
<author>Ralls, Kim</author>
<title>Midnight Rain</title>
<genre>Fantasy</genre>
<price>5.95</price>
<publish_date>2000-12-16</publish_date>
<description>A former architect battles corporate zombies,
an evil sorceress, and her own childhood to become queen
of the world.</description>
</book></room>
</library>`
我需要得到这个:
`<Books><book id="bk101">
<author>Gambardella, Matthew</author>
<title>XML Developer's Guide</title>
<genre>Computer</genre>
<price>44.95</price>
<publish_date>2000-10-01</publish_date>
<description>An in-depth look at creating applications
with XML.</description>
</book><book id="bk102">
<author>Ralls, Kim</author>
<title>Midnight Rain</title>
<genre>Fantasy</genre>
<price>5.95</price>
<publish_date>2000-12-16</publish_date>
<description>A former architect battles corporate zombies,
an evil sorceress, and her own childhood to become queen
of the world.</description>
`
我真的不知道该怎么办…你能给我建议吗我不能使用xpath。
首先打开要处理元素的文档:
$doc = new DOMDocument();
$doc->recover = true;
$doc->loadXML($buffer);
然后创建一个新文档,将元素添加到其中:
$books = new DOMDocument();
$books->preserveWhiteSpace = false;
$books->formatOutput = true;
$books->loadXML('<Books/>');
然后将<book>
元素节点从第一个文档导入第二个文档,然后将它们附加到文档元素:
foreach ($doc->getElementsByTagName('book') as $book) {
$book = $books->importNode($book, true);
$books->documentElement->appendChild($book);
}
然后,您可以重新加载文档以进行格式化并输出它:
$books->loadXML($books->saveXML());
$books->save('php://output');
输出:
<?xml version="1.0"?>
<Books>
<book id="bk101">
<author>Gambardella, Matthew</author>
<title>XML Developer's Guide</title>
<genre>Computer</genre>
<price>44.95</price>
<publish_date>2000-10-01</publish_date>
<description>An in-depth look at creating applications
with XML.</description>
</book>
<book id="bk102">
<author>Ralls, Kim</author>
<title>Midnight Rain</title>
<genre>Fantasy</genre>
<price>5.95</price>
<publish_date>2000-12-16</publish_date>
<description>A former architect battles corporate zombies,
an evil sorceress, and her own childhood to become queen
of the world.</description>
</book>
</Books>