duanhan4763 2019-07-05 07:36
浏览 108

如何在第一个元素xpath中找到元素的出现

With a XML-structure like this:

<w:document>
    <w:body>
      <w:p>{textcontent}</w:p>
      <w:p>
          <w:drawing>
          </w:drawing>
      </w:p>
      <w:p>{no textcontent}</w:p>
      <w:p>
          <w:drawing>
          </w:drawing>
      </w:p>
      <w:p>{no textcontent}</w:p>
      <w:p>text..</w:p>

      <w:tbl>three</w:tbl>
      <w:p>four</w:p>
  </w:body>
</w:document>

I want to check occurrence of and count nr of drawings

I've tried this:

$document = new DOMDocument(); 
$document->loadXML($xml_str);
$xpath = new DOMXpath($document);
$xpath->registerNamespace(
   'wspace', 'http://schemas.openxmlformats.org/wordprocessingml/2006/main'
);

$pindex = 0;
foreach ($xpath->evaluate('//wspace:p') as $index => $p_node) 
{
    if (strlen($p_node->textContent)>0) {

        //I just want to know if drawing exists in this $p_node..
        //if the the node contains any content
        $child_nodes = $xpath->evaluate('//wspace:drawing', $p_node);
        var_dump($child_nodes[0]);
        $pindex++;
        //But I get an object for each pnode. I just want an object when there
        //is an actualy <w:drawing> inside of <p> (item with index 1,3 in above example)
    }
}   

How do I check nr of occurences for the <w:p><w:drawing> ?

I could do like this to count the occurences:

foreach ($xpath->evaluate('//wspace:p//wspace:drawing') as $index => $node) 
{
    var_dump($node);
}  

but I need the index of the p ($pindex) as well.

I've also been trying with evaluate('/child'), evaluate('node()/child') without success.

What is going wrong with my expression?

  • 写回答

2条回答 默认 最新

  • dongshadu4498 2019-07-05 12:20
    关注

    Strictly from the xpath angle:

    Adding

    <root  xmlns:w='http://schemas.openxmlformats.org/wordprocessingml/2006/main'>
    [your xml above]
    </root>
    

    before and after your xml and trying

    count(//w:p/w:drawing)
    

    gave the output:

    2.0

    If you need an integer instead of float, change the expression to

    round(count(//w:p/w:drawing))
    

    Hope that helps with the rest.

    评论

报告相同问题?

悬赏问题

  • ¥15 有赏,i卡绘世画不出
  • ¥15 如何用stata画出文献中常见的安慰剂检验图
  • ¥15 c语言链表结构体数据插入
  • ¥40 使用MATLAB解答线性代数问题
  • ¥15 COCOS的问题COCOS的问题
  • ¥15 FPGA-SRIO初始化失败
  • ¥15 MapReduce实现倒排索引失败
  • ¥15 ZABBIX6.0L连接数据库报错,如何解决?(操作系统-centos)
  • ¥15 找一位技术过硬的游戏pj程序员
  • ¥15 matlab生成电测深三层曲线模型代码