开发者

How to get values of child nodes with QDomDocument?

开发者 https://www.devze.com 2023-01-12 18:06 出处:网络
A recieve a string like this: <invoke name=\"CanClose\" returntype=\"xml\"> <arguments> <string># 998.40</string>

A recieve a string like this:

<invoke name="CanClose" returntype="xml">
   <arguments>
       <string># 998.40</string>
       <number>49920</number>
   </arguments>
</invoke>

I'd like to use QDomDocument to get the values of arguments' child nodes by their index (I would like to extract the strings "# 998.40" and "49920" in the exa开发者_运维知识库mple).

This is what I tried:

QString argument(int index)
{
    QDomNode arg = xml->elementsByTagName("arguments").at(index);
    return arg.nodeValue();
}

But even arg was empty. What am I doing wrong here?

Thanks in advance.


So apparently the text inside a node is a node itself, too. This is how it works:

QString argument(int index)
{
    QDomNode arg = xml->firstChild().namedItem("arguments");
    return arg.childNodes().at(index).firstChild().nodeValue();
}


elementsByTagName() returns a list of all nodes (elements actually) with tag name "arguments" in the nodes subtree. .at() returns one of those "arguments" elements from the list, not their children. If you want the children, you need to iterate over their respective childNodes().


This function returns a QDomNodList from which there is an item function to get each node (and a count to know how many there are)

From this I would say the code probably should be

http://doc.trolltech.com/3.3/qdomdocument.html#elementsByTagName

http://doc.trolltech.com/3.3/qdomnodelist.html#item

QString argument(int index) 
{ 
    QDomNode arg = xml->elementsByTagName("arguments").item(index); 
    return arg.nodeValue(); 
}

You probably should check using the NodeList count that the index is within bounds.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号