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 高价求中通快递查询接口
  • ¥15 解决一个加好友限制问题 或者有好的方案
  • ¥15 关于#java#的问题,请各位专家解答!
  • ¥15 急matlab编程仿真二阶震荡系统
  • ¥20 TEC-9的数据通路实验
  • ¥15 ue5 .3之前好好的现在只要是激活关卡就会崩溃
  • ¥50 MATLAB实现圆柱体容器内球形颗粒堆积
  • ¥15 python如何将动态的多个子列表,拼接后进行集合的交集
  • ¥20 vitis-ai量化基于pytorch框架下的yolov5模型
  • ¥15 如何实现H5在QQ平台上的二次分享卡片效果?