很难弄清楚如何存储解析过的xml - simpleXML


Trouble figuring out how parsed xml is stored - simpleXML

假设我的XML是这样的:

<?xml version="1.0"?>
<lists>
    <list
        path=".">
        <entry
            kind="dir">
            <name>Assignment1.1</name>
            <commit
                revision="1668">
                <author>netid</author>
                <date>2011-09-07T03:03:58.367692Z</date>
            </commit>
        </entry>
        <entry
            kind="file">
            <name>Assignment1.1/.classpath</name>
            <size>397</size>
            <commit
                revision="1558">
                <author>netid</author>
                <date>2011-09-06T17:00:52.998920Z</date>
            </commit>
      .
      .
      .
    </list>
</lists>

我用

将它存储在SimpleXML对象中

$xml_list = simplexml_load_file(dirname(__FILE__).'/svn_list.xml');

如何访问包含1558的修订变量?

我似乎不能弄清楚使用echoprint_r的组合。

SimpleXML使用一组实现迭代器的类来遍历它们,因此您可以使用foreach遍历每个节点,然而,加载XML后导航XML的最简单方法是使用SimpleXMLElement::xPath()。要获得修订1558,您可以拨打以下电话:

$commit = $xml_list->xpath('//list/entry/commit[@revision="1558"]');

这将返回<commit revision="1558">下面的节点,然后您可以从扩展ArrayObject$commit变量访问它们。

要获取<author>元素的实际内容,您必须执行以下操作:

print((string)$commit[0]->author);

SimpleXMLElement实例需要转换为类型以公开其实际值。

同样,如果要转储$commit的内容以查看其子节点,最简单的方法是如下所示调用asXml()方法:

print($commit[0]->asXml());

您正面临困难,因为您在XML文件上有错误,</entry>标记未关闭。

可以这样遍历

<?php
$xml='<lists>
    <list>
        <entry
            kind="dir">
            <name>Assignment1.1</name>
            <commit
                revision="1668">
                <author>netid</author>
                <date>2011-09-07T03:03:58.367692Z</date>
            </commit>
        </entry>
        <entry
            kind="file">
            <name>Assignment1.1/.classpath</name>
            <size>397</size>
            <commit
                revision="1558">
                <author>netid</author>
                <date>2011-09-06T17:00:52.998920Z</date>
            </commit>
            </entry>
    </list>
</lists>';
$xml = simplexml_load_string($xml);
foreach ($xml->list->entry[0]->commit->attributes() as $a=>$v)
{
    echo $v;
}

OUTPUT :

1668