xml base and relative query combination in qml
I have the following xml :
<response>
<id>...<开发者_开发百科;/id>
<category_id>...</category_id>
<name>...</name>
<detail>
<resource>
<label>...</label>
<value>...</value>
</resource>
<resource>
<label>...</label>
<value>...</value>
</resource>
</detail>
<price>...</price>
<currency>...</currency>
</response>
I need to get the id, name as well as label and value from one XmlListModel
I have the following code:
XmlListModel {
id: model
query:"/response"
source:"xml source"
XmlRole { name: "name"; query: "name/string()" }
XmlRole { name: "id"; query:"id/number()" }
XmlRole { name: "label"; query: "detail/resource/label/string()" }
XmlRole { name: "value"; query:"detail/resource/value/string()" }
}
What is wrong with this code? Thanks.
The problem is, that the xpath query detail/resource/label/string()
does not select exactly one node, because there are multiple resource
nodes. If you don't need all resource
nodes, you can select only the first one with detail/resource[1]/label/string()
.
If you need all resource
nodes, you can use an additional XmlModel
:
import QtQuick 1.0
Item {
property string xmlData:
"<response>
<id>1234</id>
<category_id>...</category_id>
<name>The Name</name>
<detail>
<resource>
<label>Res1</label>
<value>1</value>
</resource>
<resource>
<label>Res2</label>
<value>2</value>
</resource>
</detail>
<price>...</price>
<currency>...</currency>
</response>"
// model for general data
XmlListModel {
id: model
xml: xmlData
query:"/response"
XmlRole { name: "name"; query: "name/string()" }
XmlRole { name: "id"; query: "id/number()" }
}
// model for resource data
XmlListModel {
id: resModel
xml: xmlData
query: "/response/detail/resource"
XmlRole { name: "label"; query: "label/string()" }
XmlRole { name: "value"; query: "value/string()" }
}
}
精彩评论