我有以下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>
我需要从一个XmlListModel
获取id,name以及label和value我有以下代码:
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()" }
}
这段代码有什么问题? 感谢。
答案 0 :(得分:2)
问题是,xpath查询detail/resource/label/string()
没有选择一个节点,因为有多个resource
个节点。如果您不需要所有resource
个节点,则只能使用detail/resource[1]/label/string()
选择第一个节点。
如果您需要所有resource
个节点,则可以使用其他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()" }
}
}