Xform xml解析

时间:2014-03-14 06:08:53

标签: php xml xml-parsing xforms javarosa

在xform xml中,我想解析xml并访问节点的id。它是xform xml,我想访问节点test_geopoint(id = test_geopoint)的id。但是每个xform xml的节点名称都会改变。

    <?php
$xmlstr = <<<XML <?xml version="1.0"?>
    <h:html xmlns="http://www.w3.org/2002/xforms" xmlns:ev="http://www.w3.org/2001/xml-events" xmlns:h="http://www.w3.org/1999/xhtml" xmlns:jr="http://openrosa.org/javarosa" xmlns:orx="http://openrosa.org/xforms/" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
      <h:head>
        <h:title>test_geopoint</h:title>
        <model>
          <instance>
            <test_geopoint id="test_geopoint">
              <name/>
              <geopoint/>
              <meta>
                <instanceID/>
              </meta>
            </test_geopoint>
          </instance>

      </h:body>
    </h:html> $XML;

我尝试了这样的代码,但没有在<instance>.

之后访问节点的id
$movies = new SimpleXMLElement($xmlstr);
echo $movies->model->instance->children()[0]['id'];
and
echo $movies->head->title->model->instance->children()[0]['id'];

如何在php中找到<instance>旁边的节点的id?

2 个答案:

答案 0 :(得分:1)

以下示例与您期望的相同,使用方式与我访问的方式相同,即数组中的name。你应该提到instanceId

$xmlstr = <<<XML
<?xml version='1.0' standalone='yes'?>
<movies>
 <movie>
  <title>PHP: Behind the Parser</title>
  <characters>
   <character>
    <name>Ms. Coder</name>
    <actor>Onlivia Actora</actor>
   </character>
   <character>
    <name>Mr. Coder</name>
    <actor>El Act&#211;r</actor>
   </character>
  </characters>
  <plot>
   So, this language. It's like, a programming language. Or is it a
   scripting language? All is revealed in this thrilling horror spoof
   of a documentary.
  </plot>
  <great-lines>
   <line>PHP solves all my web problems</line>
  </great-lines>
  <rating type="thumbs">7</rating>
  <rating type="stars">5</rating>
 </movie>
</movies>
XML;

$movies = new SimpleXMLElement($xmlstr);


echo '<pre>';

foreach($movies as $moviesdata){
    foreach($moviesdata as $moviesdatavalues){
        foreach($moviesdatavalues as $mdvk=>$mdn){
            foreach($mdn as $c=>$v){
                    if($c == 'name'){
                        echo $v."\n";
                }
            }
        }
    }
}
?>

答案 1 :(得分:0)

默认命名空间是http://www.w3.org/2002/xforms,因此html的每个未加前缀的元素后代都在该命名空间中;包括你的实例数据。

尝试将空名称空间(xmlns="")添加到实例数据中......

<model>
    <instance>
        <test_geopoint xmlns="" id="test_geopoint">
            <name/>
            <geopoint/>
            <meta>
                <instanceID/>
            </meta>
        </test_geopoint>
    </instance>
    <bind nodeset="/test_geopoint/name" type="string"/>
    <bind nodeset="/test_geopoint/geopoint" type="geopoint"/>
    <bind calculate="concat('uuid:', uuid())" nodeset="/test_geopoint/meta/instanceID" readonly="true()" type="string"/>
</model>