2013-02-15 107 views
0

我想读结构如下读取XML元素

<dictionary> 
<head> 

<DNUM /> 
<DEF value="definition1" /> 
<EXAMPLE value="example of 1" /> 
<EXAMPLE value="example of 1" /> 

<DNUM /> 
<DEF value="definition2" /> 
<EXAMPLE value="example of 2" /> 
<EXAMPLE value="example of 2" /> 
<EXAMPLE value="example of 2" /> 
<EXAMPLE value="example of 2" /> 

<DNUM /> 
<DEF value="definition3" /> 
<EXAMPLE value="example of 3" /> 


</head> 
</ dictionary> 

一个代码somehing像下面我能读“头”标签内的所有定义或示例XML文件

$result = $xml->xpath('//dictionary/head'); 
while(list(, $node) = each($result)) { 
    foreach($node->DEF as $def){ 
     echo $def["value"]."<br>\n"; 
    } 
} 

但我想得到每个定义和这个定义的例子。我认为DNUM标签可以用于这个,但由于它没有打开和关闭分开我无法找到我如何能得到我想要的结果。

+0

你确定的XML是免费的错误? – ajreal 2013-02-15 18:48:13

+0

@ajreal:这是Windows字典应用程序使用的结构。它似乎运作正常。 – mustafa 2013-02-15 18:54:35

+0

这个xml是无效的。它应该是不是用于关闭 – Rohit 2013-02-15 19:21:55

回答

0

我不知道如果我理解你的问题,但如果你需要找到DEFS和这样的例子DEF它可以像

$result = $xml->xpath('//dictionary/head/DEF'); 
while(list(, $node) = each($result)) { 
    foreach($node->EXAMPLE as $example){ 
     echo $example["value"]."<br>\n"; 
    } 
} 
+0

不行,它不工作。 – mustafa 2013-02-15 19:42:21

0

为什么不使用的SimpleXMLElement?

$sxe = new SimpleXMLElement($xml); 

$def = $sxe->head->dictionary->DEF->attributes(); //you can foreach this 
//or 
$def = $sxe['head']['dictionary']['DEF']->attributes(); //you can foreach this 

你可以用类似的方式得到这些例子。 SXE可以像对象或数组一样使用,并通过foreach进行迭代。

我个人认为SimpleXMLElement是处理XML和PHP的最简单方法。

延伸阅读: http://www.php.net/manual/en/class.simplexmlelement.php

0

我以这种方式解决问题。

$result = $xml->xpath('//dictionary/headword/*[name()="DEF" or name()="EXAMPLE"]'); 
foreach($result as $res){ 
    echo $res["value"]."<br>"; 
} 
0

由于您的XML结构不是分层的,您只能计数。例如,下面的DNUM元素的个数:

$name  = 'DNUM'; 
$elements = $xml->xpath("//$name"); 
$count = count($elements); 
foreach ($elements as $index => $element) { 
    $count--; 
    echo "Iteration $index\n"; 
    foreach ($element->xpath("following-sibling::*[count(./following-sibling::$name) = $count]") as $following) { 
     echo $following->asXML(), "\n"; 
    } 
    echo "\n"; 
} 

输出例:

Iteration 0 
<DEF value="definition1"/> 
<EXAMPLE value="example of 1"/> 
<EXAMPLE value="example of 1"/> 

Iteration 1 
<DEF value="definition2"/> 
<EXAMPLE value="example of 2"/> 
<EXAMPLE value="example of 2"/> 
<EXAMPLE value="example of 2"/> 
<EXAMPLE value="example of 2"/> 

Iteration 2 
<DEF value="definition3"/> 
<EXAMPLE value="example of 3"/> 
+0

我不太了解跟随兄弟姐妹的用法。我刚开始阅读有关它。无论如何,代码只输出“迭代0/1/2”。 – mustafa 2013-02-17 16:12:28

+0

@mustafa:输出结果在anser中给出。如果你只看到你写的东西,你会发现你需要在浏览器中查看源代码,使用浏览器窗口自然不会显示你的XML。 – hakre 2013-02-18 07:02:04