【问题标题】:How to read the content of xml with same multiple nodenames with xpath in php?如何在php中使用xpath读取具有相同多个节点名的xml内容?
【发布时间】:2018-08-21 14:42:44
【问题描述】:

我有一个 xml 字符串,我必须在其中检查特定字符。 为了检查它,我必须遍历所有节点值。

xml如下:

<?xml version="1.0" encoding="UTF-8"?>
  <s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/">
    <s:Body>
     <epos-print xmlns="http://www.epson-pos.com/schemas/2014/05/epos-print"><pulse/>
      <text align="center" ul="0" em="0" dw="1" dh="1" smooth="1" lang="de">Shoppingqueen</text>
      <feed/>
     <text align="center" ul="0" em="0" dw="0" dh="0" smooth="1" lang="de">Text me</text>
     <feed/>
     <text align="center" ul="0" em="0" dw="0" dh="0" smooth="1" lang="de">Hello People</text>
      <feed/>
      <text align="left" ul="0" em="0" dw="0" dh="0" smooth="0" lang="de">Hello world</text>
     <feed line="2"/>
     <text align="center" ul="0" em="0" dw="0" dh="0" smooth="0" lang="de">Some text</text>
     <feed line="2"/>
     <text align="left" ul="0" em="0" dw="0" dh="0" smooth="0" lang="de">Chocolate                         20,00 EUR A</text>
     <feed/>
     <text align="left" ul="1" em="0" dw="0" dh="0" smooth="0" lang="de">Apples                      15,00 EUR A</text>
     <feed/>
     <text align="left" ul="0" em="1" dw="0" dh="0" smooth="0" lang="de">Onion                   35,00 EUR  </text>
     <feed line="2"/>
     <text align="left" ul="0" em="0" dw="0" dh="0" smooth="0" lang="de">Cash                     35,00 EUR  </text>
     <cut/>
  </epos-print>
 </s:Body>
</s:Envelope>

这只是我尝试过的一种方法:

$xml = new SimpleXMLElement($xmlText);

$texts = $xml->xpath("epos-print/text");

while(list( , $text) = each($texts)) {
    echo 'b/c: ',$text,"\n";
}

我认为 xpath 是最容易使用的。 我尝试了很多不同的类型,但没有得到任何结果。 请帮忙。

【问题讨论】:

    标签: php xml xpath xml-parsing


    【解决方案1】:

    主要问题是您所追求的元素具有默认命名空间(在epos-print 元素中您有xmlns="http://www.epson-pos.com/schemas/2014/05/epos-print")。

    这意味着你的 XPath 需要使用它来引用元素,所以首先将它注册到文档中(我使用 'd' 作为前缀来缩写),然后在你的元素名称前面加上这个新的命名空间......

    $xml = new SimpleXMLElement($xmlText);
    $xml->registerXPathNamespace("d", "http://www.epson-pos.com/schemas/2014/05/epos-print");
    $texts = $xml->xpath("//d:epos-print/d:text");
    
    foreach ( $texts as $text ) {
        echo 'b/c: ',(string)$text,"\n";
    }
    

    同样使用//d:epos-print/d:text 和'//' 开头意味着epos-print 可以位于文档中的任何位置。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-07-19
      • 1970-01-01
      相关资源
      最近更新 更多