在简单的XML文件上使用DOMDocument PHP类


Using DOMDocument PHP classes on simple XML file

我的XML文档如下。

<?xml version="1.0" encoding="utf-8"?>
<userSettings>
    <tables>
        <table id="supertable">
            <userTabLayout id="A">{"id":"colidgoeshereX"}</userTabLayout>
            <userTabLayout id="B">{"id":"colidgoeshereY"}</userTabLayout>
        </table>
        <table id="almost-supertable">
            <userTabLayout id="A">{"id":"colidgoeshereC"}</userTabLayout>
            <userTabLayout id="B">{"id":"colidgoeshereD"}</userTabLayout>
        </table>
    </tables>
</userSettings>

我使用以下PHP代码加载文件(DOMDocument),然后DomXpath遍历文档

<?php
...
    $xmldoc = new DOMDocument();
    $xmldoc->load ($filename);
    $xpath = new DomXpath($xmldoc);
    $x = $xpath->query("//tables/table");
    $y = $x->item(0);
...
?>

$y变量现在包含一个DOMElement对象,nodeValue属性包含如下字符串:

["nodeValue"]=>
string(81) "
        {"id":"colidgoeshereX"}
        {"id":"colidgoeshereY"}
"

我的问题是,<userTabLayout>节点发生了什么?为什么我不认为这是<table>节点的子节点?如果我想访问<userTabLayout id="B">节点,我该怎么做呢?

通常我会阅读关于这类东西的文档,但是官方PHP页面上的官方文档真的很少。

我的问题是,<userTabLayout>节点发生了什么?

什么也没发生。<userTabLayout>元素是$yDOMElement的子元素。

为什么我不认为这是<table>节点的子节点?

因为您没有使用nodeValue字段查找子节点。

如果我想访问<userTabLayout id="B">节点,我该怎么做?

通过遍历文档,例如通过childNodes字段(surprise)访问子节点。

通常我会阅读关于这类东西的文档,但是官方PHP页面上的官方文档真的很少。

这是因为DOM已经被W3C文档化了,例如:http://www.w3.org/TR/1998/REC-DOM-Level-1-19981001/

由于该链接是规范的,因此可能有点技术性,因此很难进行工作,但是您可以认为它是完整的(例如,如果需要了解它,请检查其真实性)。一旦理解了指定的DOM,您就可以使用任何可用的DOM文档,例如在MDN中,甚至在Javascript (W3C的两种默认实现之一)中,它在PHP中的工作原理类似(特别是用于遍历或Xpath的工作方式)。

祝你阅读愉快!

不用DomXpath也可以工作。

$xmlS = '
<userSettings>
    <tables>
        <table id="supertable">
            <userTabLayout id="A">{"id":"colidgoeshereX"}</userTabLayout>
            <userTabLayout id="B">{"id":"colidgoeshereY"}</userTabLayout>
        </table>
        <table id="almost-supertable">
            <userTabLayout id="A">{"id":"colidgoeshereC"}</userTabLayout>
            <userTabLayout id="B">{"id":"colidgoeshereD"}</userTabLayout>
        </table>
    </tables>
</userSettings>
';
$xmldoc = new DOMDocument();
$xmldoc->loadXml($xmlS);
$table1 = $xmldoc->getElementsByTagName("tables")->item(0);
$userTabLayoutA = $table1->getElementsByTagName("userTabLayout")->item(0);
$userTabLayoutB = $table1->getElementsByTagName("userTabLayout")->item(1);
echo $userTabLayoutA->nodeValue; // {"id":"colidgoeshereX"}
echo $userTabLayoutB->nodeValue; // {"id":"colidgoeshereY"}

如您所见,您可以使用getElementsByTagName逐个访问所有元素,并指定您想要的项目。