php DomDocument - 找到空文本节点?

时间:2014-12-24 08:33:09

标签: php xml xpath domdocument

获取这个非常基本的XML文档(这只是一个基本的例子)

<?xml version="1.0" encoding="UTF-8"?>

<books>
    <book>first title<sep/>first author</book>
    <book>second title<sep/>second author</book>
    <book>third title<sep/>third author</book>
    <book><sep/>fourth author</book>
</books>

问题很简单......如何插入第四本书的标题?
如何自动检测到第四本书没有设置标题?

我真正需要的是php DOMDocument告诉我前一个<sep/>前面有一个空文本节点。
但是使用DOMDocument,节点根本不存在:

<?php

$path = './books.xml';

$dom = new DOMDocument();
$dom->load($path);

$books = $dom->getElementsByTagName('book');

foreach ($books as $index => $book) {
    echo $book->childNodes->length . ' children' . PHP_EOL;
}

上面的代码只显示了最后一个book节点的2个子节点。

使用Xpath /books/book[4]/text()[1]指向第四本书的“作者”文本节点,并且不指向<sep/>

前面的空文本节点

如果这不是很清楚,请告诉我......

提前感谢您的帮助!

1 个答案:

答案 0 :(得分:0)

它没有告诉你那里有一个空文本节点,因为那里没有文本节点 - 这很简单。选择该书的xpath表达式为:

/books/book[not(sep/preceding-sibling::text())]

实施例

$xml = <<<'XML'
<?xml version="1.0" encoding="UTF-8"?>

<books>
    <book>first title<sep/>first author</book>
    <book>second title<sep/>second author</book>
    <book>third title<sep/>third author</book>
    <book><sep/>fourth author</book>
</books>
XML;

$dom = new DOMDocument();
$dom->loadXML($xml);
$xpath = new DOMXPath($dom);

$query = '/books/book[not(sep/preceding-sibling::text())]';
foreach ($xpath->query($query) as $book) {
    $title = $dom->createTextNode("fourth title");
    $book->insertBefore($title, $book->firstChild);
    echo $dom->saveXML($book), "\n";
}

输出:

<book>fourth title<sep/>fourth author</book>