我使用简化的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 。
答案 0 :(得分:0)
首先打开要处理元素的文档:
$doc = new DOMDocument();
$doc->recover = true;
$doc->loadXML($buffer);
然后创建一个新元素,将元素添加到:
$books = new DOMDocument();
$books->preserveWhiteSpace = false;
$books->formatOutput = true;
$books->loadXML('<Books/>');
然后将<book>
元素节点从第一个文档导入到第二个文档中,然后将它们附加到document-element:
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>