扩展二级 XML 节点的名称/值对


Extracing name / value pairs for second-level XML nodes

好的,我有一些以下格式的基本XML:

<application>
   <authentication>
      <id>26</id>
      <key>gabe</key>
   </authentication>
   <home>
      <address>443 Pacific Avenue</address>
      <city>North Las Vegas</city>
      <state>NV</state>
      <zip>89084</zip>
   </home>
</application>

我使用 simplexml_load_string() 将上述 XML 加载到变量中,如下所示:

$xml = simplexml_load_string($xml_string);

我想提取第二个节点的名称/值对,例如,我想忽略<authentication><home>节点。我只对这些第一级节点中的子节点感兴趣:

  1. 编号
  2. .key
  3. 地址
  4. 城市
  5. .zip

所以我正在寻找一个 foreach 循环,它将提取上述 6 个名称/值对,但忽略"较低级别"的名称/值对。 下面的代码只打印<authentication><home>节点的名称/值对(我想忽略):

foreach($xml->children() as $value) {
  $name = chop($value->getName());
  print "$name = $value";
}

有人可以帮助我处理仅提取上述 6 个节点的名称/值对的代码吗?

好的,所以我审查了你的建议(Oliver A.)并提出了以下代码:

$string = <<<XML
<application>
   <authentication>
      <id>26</id>
      <key>gabe</key>
   </authentication>
   <home>
      <address>443 Pacific Avenue</address>
      <city>North Las Vegas</city>
      <state>NV</state>
      <zip>89084</zip>
   </home>
</application>
XML;
$xml = new SimpleXMLElement($string);
/* Search for <a><b><c> */
$result = $xml->xpath('/application/*/*');
while(list( , $node) = each($result)) {
    echo '/application/*/*: ',$node,"'n";
}

这将返回以下内容:

/application/*/*: 26
/application/*/*: gabe
/application/*/*: 443 Pacific Avenue
/application/*/*: North Las Vegas
/application/*/*: NV
/application/*/*: 89084

这是进步,因为我现在只有二级元素的值。 伟大! 问题是我需要为名称和值对分配一个变量名称。 似乎我无法提取出每个二级节点的名称。 我错过了什么吗?

您可以使用 xpath:http://php.net/manual/en/simplexmlelement.xpath.php

随着路径

/application/*/*

您将获得所有二级元素。

编辑:

$string = <<<XML
<application>
   <authentication>
      <id>26</id>
      <key>gabe</key>
   </authentication>
       <home>
          <address>443 Pacific Avenue</address>
          <city>North Las Vegas</city>
          <state>NV</state>
          <zip>89084</zip>
       </home>
    </application>
XML;
    $xml = new SimpleXMLElement($string);
   foreach($xml->xpath('/application/*/*') as $node){
        echo "{$node->getName()}: $node,'n";
   }