我有这个XML:
<picture id="2">
<title>B</title>
</picture>
<picture id="3">
<title>C</title>
</picture>
<picture id="0">
<title>A</title>
</picture>
试图实现这个目标:
<picture id="1">
<title>B</title>
</picture>
<picture id="2">
<title>C</title>
</picture>
<picture id="0">
<title>A</title>
</picture>
使用它来获取'id'属性值列表:
$objXML = new SimpleXMLElement(XML_FILE_NAME, null, true);
$picture = $objXML->xpath('picture');
$arrayCurrent = array();
foreach($picture as $value) {
$arrayCurrent[] = (string)$value['id'];
}
sort($arrayCurrent); // put XML into numerical 'id' order
print_r($arrayCurrent);
它返回:数组([0] =&gt; 0 [1] =&gt; 2 [2] =&gt; 3) 任何想法如何重新索引如此:0,1,2并将相应的“id”属性保存回XML文档中的正确位置?
谢谢,安迪
答案 0 :(得分:0)
在XML
相同级别的节点顺序无关紧要,你不能通过理论,练习用户其他库来做到这一点。
答案 1 :(得分:0)
维持数字id顺序并使其连续:
$objXML = new SimpleXMLElement(XML_FILE_NAME, null, true);
$picture = $objXML->xpath('picture');
usort($picture, create_function('$a,$b', 'return (string)$a["id"] - (string)$b["id"];'));
foreach ($pictures as $index => $node) $node["id"] = $index;