在php类中处理xml文件时出错

时间:2016-03-30 19:48:14

标签: php xml dom

我在PHP中创建了一个类,它将为我处理XML文件(使用DOM)。我现在需要的类的唯一功能是'DeleteNodes',它取决于其他功能。这是班级:

class HandleXML{
    public $DomElem;
    private $path;
    private $node;
    private $parent;
    private $nodes;

    function HandleXML($path){
        $this->path=$path;
        $this->DomElem=new DOMDocument();
        $this->DomElem->Load($path);

        //Default values
        $this->parent=$this->DomElem->documentElement;
    }
    function SelectNodes($tagName){
        $this->nodes=$this->DomElem->getElementsByTagName($tagName);
        return $this->nodes;
    }
    function SelectNodeById($id){
        $this->node=$this->nodes->item($id);
        //return $this->node;
    }
    function DeleteNode(){
        $this->node->parentNode->removeChild($this->node);  //Line 91-here's the error
    }
    function DeleteNodes(){
        for ($i=$this->nodes->length; $i >=0 ; $i--) { 
            $this->SelectNodeById($i);
            $this->DeleteNode();
        }
    }
}

以下是我处理该类的方法(来自另一个PHP页面):

$file=new HandleXML("../Data files/XML Data/Data.xml");

$file->SelectNodes("announce");
$file->DeleteNodes();

这是Data.xml文件(用另一种语言):

<?xml version="1.0" encoding="UTF-8"?>
<information>
    <announce>
        <picture>calendar.png</picture>
        <text>Anunt in vederea inscrierii in clasa V - a</text>
    </announce>
    <announce>
        <picture>Janitor.png</picture>
        <text>Anunt in vedera angajarii unui ingrijitor</text>
</information>

错误说:“试图在第91行获取非对象的属性”。看起来变量$ node还没有被for循环中的'SelectNodeById'函数设置。那是为什么?

0 个答案:

没有答案