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 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂
  • ¥15 wordpress 产品图片 GIF 没法显示