doukai2839 2010-10-20 10:30
浏览 130
已采纳

选择一些但不是所有子节点

I have the following XML structure:

<?xml version="1.0" encoding="ISO-8859-1"?>
<articles>
  <article id="1">
    <title>Article title 001</title>
    <short>Short text</short>
    <long>Long text</long>
  </article>
  <article id="2">
    <title>Article title 002</title>
    <short>Short text</short>
    <long>Long text</long>
  </article>
</articles>

I want to select only <title> and <short>.

Currently using this to display everything:

 $queryResult = $xpathvar->query('//articles/article'); // works fine grabs all articles
 foreach($queryResult as $result){
   echo $result->textContent;
 }

The expected output would be:

Article title 001

Short text

Any assistance would be greatly appreciated.

Working solution!

if ($artId == "") {
    $queryResult = $xpathvar->query('//articles/article/*'); // grab all children
    foreach($queryResult as $result){
      if($result->nodeName === 'title' || $result->nodeName === 'short') {
          echo $result->textContent;
      }
    }
}else{
    $queryResult = $xpathvar->query(sprintf('//articles/article[@id="%s"]/*', $artId)); // Show requested article
    foreach($queryResult as $result){
      if($result->nodeName === 'title' || $result->nodeName === 'long') {
          echo $result->textContent;
      }
    }
}
  • 写回答

2条回答 默认 最新

  • douzhuangxuan3268 2010-10-20 10:35
    关注

    You can use

    /articles/article/*[name()="title" or name()="short"]
    

    which would only return children of any "articles/article" with an element name of "title" or "short".


    As an alternative, change the XPath to /articles/article/* to fetch all childNodes of article and when iterating $results check if DOMNode::nodeName is "title" or "short", e.g.

    $queryResult = $xpathvar->query('/articles/article/*'); // grab all children
    foreach($queryResult as $result){
      if($result->nodeName === 'title' || $result->nodeName === 'short') {
          echo $result->textContent;
      }
    }
    

    If you dont want to change the XPath, you have to iterate the childNodes of the article, e.g.

    $queryResult = $xpathvar->query('/articles/article');
    foreach($queryResult as $result) {
      foreach($result->childNodes as $child) {       
      if($child->nodeName === 'title' || $child->nodeName === 'short') {
          echo $child->textContent;
      }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 微信会员卡接入微信支付商户号收款
  • ¥15 如何获取烟草零售终端数据
  • ¥15 数学建模招标中位数问题
  • ¥15 phython路径名过长报错 不知道什么问题
  • ¥15 深度学习中模型转换该怎么实现
  • ¥15 HLs设计手写数字识别程序编译通不过
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向
  • ¥15 如何用python向钉钉机器人发送可以放大的图片?