DOM XML解析限制结果值

时间:2013-01-15 12:35:32

标签: php dom xml-parsing

我坚持这个,无法在网上找到答案。我想使用DOM来加载XML。 我有一个XML,具有以下方案:

<type1>
   <other>...</other>
   <number>bla</number>
   <other>...</other>
</type1>
<type1>
   <other>...</other>
   <number>bla</number>
   <other>...</other>
</type1>
...
<type2>
   <other>...</other>
   <number>bla</number>
   <other>...</other>
</type2>
<type2>
   <other>...</other>
   <number>bla</number>
   <other>...</other>
</type2>

type1和type2的数据都会多次出现。标签号出现在两种类型中。 当我使用

$searchNode = $xmlHandler->getElementsByTagName("number"); 

我得到两种类型的数字。我怎样才能得到type1或type2的数字?

更新: 根据Kami和Ikku的建议,我已经为DOM解决了这个问题。工作代码下方:

<?php  
$xmlHandler = new DOMDocument();
$xmlHandler->load("xmldocumentname.xml");

$xpath = new DOMXPath($xmlHandler);
$searchNodes = $xpath->query("/type1");
foreach( $searchNodes as $searchNode ) { 
    $xmlItem = $searchNode->getElementsByTagName("number"); 
    $number = $xmlItem->item(0)->nodeValue; 
    $xmlItem = $searchNode->getElementsByTagName("other"); 
    $other = $xmlItem->item(0)->nodeValue; 

    echo "NUMBER=" . $number . "<br>";
    echo "OTHER=" . $other . "<br>";

}
?> 

2 个答案:

答案 0 :(得分:2)

您需要扩展搜索以允许父级的特定值。 getElementsByTagName将您限制为您要查找的代码的名称,因此无法进行常规搜索。使用更通用的搜索。我在下面的示例中使用xpath库中的simplexml

$xmlHandler = simplexml_load_file("somexmlfile.xml");

$searchNode = $xmlHandler->xpath("type1/number"); // Gets type1 numbers
$searchNode = $xmlHandler->xpath("type2/number"); // Gets type2 numbers

使用DOM执行相同操作 - 创建xpath对象还有一个额外步骤,但这是使搜索更容易的必要条件。

// Create new DOM object:
$dom = new DomDocument();
$dom->loadXML($xml);

$xpath = new DOMXPath($dom);
$searchNode = $xpath->query("type1/number");
$searchNode = $xpath->query("type2/number");

以上未经测试;所以根据需要进行修改。

答案 1 :(得分:1)

我想首先搜索所有必需的类型(1或2),然后在该结果集上搜索所需的标记名。因此,可以在一行中组合一个两步流程,您必须检查在两个步骤工作时是否可以对其进行优化。

相关问题