Xml.nodeValue 导致 "Bad node type" 错误

Xml.nodeValue causes "Bad node type" error

class Main extends Sprite 
{

    public function new() 
    {
        super();

        try 
        {
            var xml:Xml = Xml.parse("<count>6</count>");

            trace(xml.nodeType);

            for (x in xml.elementsNamed("count"))
            {
                trace(x.nodeName);
                trace(x.nodeType);
                trace(x.nodeValue);
            }
        } 
        catch (err:Dynamic) 
        {
            trace(err);
            Sys.exit(1);
        }
    }

}

输出:

Main.hx:23: 6

Main.hx:27: count

Main.hx:28: 0

Main.hx:34: Bad node type, unexpected 0

我无法完全理解nodeValue属性的运行原理。因此,我无法解决我的问题。有什么帮助吗?

P.S。我的配置是:Haxe + OpenFL targeting Neko.

elementsNamed() returns 类型 XmlType.Element 的节点,并且 docs for nodeValue 明确声明:

Returns the node value. Only works if the Xml node is not an Element or a Document.

所以 nodeValue 将适用于所有其他可能 XmlType values. In your case, the value you want to retrieve is stored in a XmlType.PCData node, and you can access it using firstChild():

for (x in xml.elementsNamed("count"))
{
    trace(x.firstChild().nodeType); // 1 - XmlType.PCData
    trace(x.firstChild().nodeValue); // 6
}

<count>6</count> 的完整结构如下所示:

[XmlType.Document] -> [XmlType.Element <count>] -> [XmlType.PCData 6]