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 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog