dqfsbvd43312 2014-12-24 08:33 采纳率: 0%
浏览 102
已采纳

php DomDocument - 找到空文本节点?

Take this very basic XML document (this is just a basic example)

<?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>

The problem is pretty simple... How do I insert the title of the fourth book ?
And how do I automatically detect that the title is not set for the fourth book ?

What I'd really need is the php DOMDocument to tell me that there is an empty text node in front of the last <sep/>.
But with DOMDocument, the node simply does not exist:

<?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;
}

The code above shows only 2 childnodes for the last book node.

And using Xpath /books/book[4]/text()[1] points to the "author" text node of the fourth book and does not point to the empty text node in front of the <sep/>

Let me know if this is not perfectly clear...

Thanks in advance for your help !

  • 写回答

1条回答 默认 最新

  • dongqiang5541 2014-12-24 08:56
    关注

    It's not telling you there is an empty text node there because there isn't a text node there - that simple. The xpath expression to pick out that book would be:

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

    Example:

    $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), "
    ";
    }
    

    Output:

    <book>fourth title<sep/>fourth author</book>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 R语言卸载之后无法重装,显示电脑存在下载某些较大二进制文件行为,怎么办
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?
  • ¥15 关于#vue.js#的问题:修改用户信息功能图片无法回显,数据库中只存了一张图片(相关搜索:字符串)
  • ¥15 texstudio的问题,
  • ¥15 spaceclaim模型变灰色