php循环xml数据与xsd架构 - 如何获取数据

时间:2014-06-06 07:26:46

标签: php xml foreach xsd

我尝试从xml文件中获取数据并且我在获取数据时遇到麻烦, 例如,我如何获得caaml:locRef值或caaml:beginPosition值?

这是迄今为止的代码:

/* a big thank you to helderdarocha */
/* – he already helped me yesterday with a part of this code */ 

$doc = new DOMDocument();
    $doc->load('xml/test.xml');

    $xpath = new DOMXpath($doc);
    $xpath->registerNamespace("caaml", "http://caaml.org/Schemas/V5.0/Profiles/BulletinEAWS");

    if ($doc->schemaValidate('http://caaml.org/Schemas/V5.0/Profiles/BulletinEAWS/CAAMLv5_BulletinEAWS.xsd')) {

        foreach ($xpath->query('//caaml:DangerRating') as $key) {
            echo $key->nodeValue;
            print_r($key);
        }

    } 

这里是来自$ key的print_r

DOMElement Object ( [tagName] => caaml:DangerRating [schemaTypeInfo] => [nodeName] => caaml:DangerRating [nodeValue] => 2014-03-03+01:00 2 [nodeType] => 1 [parentNode] => (object value omitted) [childNodes] => (object value omitted) [firstChild] => (object value omitted) [lastChild] => (object value omitted) [previousSibling] => (object value omitted) [nextSibling] => (object value omitted) [attributes] => (object value omitted) [ownerDocument] => (object value omitted) [namespaceURI] => http://caaml.org/Schemas/V5.0/Profiles/BulletinEAWS [prefix] => caaml [localName] => DangerRating [baseURI] => /Applications/MAMP/htdocs/lola/xml/test.xml [textContent] => 2014-03-03+01:00 2 ) 2014-03-04+01:00 2 

这里是xml的一部分

 <caaml:DangerRating>
      <caaml:locRef xlink:href="AT7R1"/>
      <caaml:validTime>
        <caaml:TimePeriod>
          <caaml:beginPosition>2014-03-06T00:00:00+01:00</caaml:beginPosition>
          <caaml:endPosition>2014-03-06T11:59:59+01:00</caaml:endPosition>
        </caaml:TimePeriod>
      </caaml:validTime>
      <caaml:validElevation>
        <caaml:ElevationRange uom="m">
          <caaml:beginPosition>2200</caaml:beginPosition>
        </caaml:ElevationRange>
      </caaml:validElevation>
      <caaml:mainValue>2</caaml:mainValue>
    </caaml:DangerRating>
    <caaml:DangerRating>
      <caaml:locRef xlink:href="AT7R1"/>
      <caaml:validTime>
        <caaml:TimePeriod>

谢谢!

1 个答案:

答案 0 :(得分:2)

DOMXpath :: query()/ evaluate()的第二个参数是表达式的上下文。您已经选择并迭代了DangerRating。在循环内部,您可以使用其他表达式来获取数据:

foreach ($xpath->evaluate('//caaml:DangerRating') as $dangerRating) {
  echo $xpath->evaluate(
    'string(caaml:validTime/caaml:TimePeriod/caaml:beginPosition)'
    $dangerRating
  );
}

string() Xpath函数将位置路径的第一个节点强制转换为字符串。这样您就不需要PHP中的->item(0)->nodeValue。它只适用于evaluate()。

caaml:locRef值存储在不同命名空间的属性中。因此,您需要首先注册该命名空间:

$xpath->registerNamespace("xlink", "http://www.w3.org/1999/xlink");

之后,您可以获取并转换属性节点:

$locRef = $xpath->evaluate(
 'string(caaml:locRef/@xlink:href)', $dangerRating
);