将xml数据给QStandardItemModel
时间: 2023-12-19 11:05:07 浏览: 31
可以使用`QXmlStreamReader`解析XML数据,并将解析结果存储到`QStandardItemModel`中。以下是一个示例代码:
```c++
QStandardItemModel *model = new QStandardItemModel(this);
QFile file(xmlFilePath);
if (!file.open(QFile::ReadOnly | QFile::Text)) {
qDebug() << "Failed to open file";
return;
}
QXmlStreamReader xml(&file);
QStandardItem *parentItem = model->invisibleRootItem();
while (!xml.atEnd() && !xml.hasError()) {
QXmlStreamReader::TokenType token = xml.readNext();
if (token == QXmlStreamReader::StartDocument) {
continue;
}
if (token == QXmlStreamReader::StartElement) {
if (xml.name() == "root") {
continue;
}
QStandardItem *item = new QStandardItem(xml.name().toString());
parentItem->appendRow(item);
parentItem = item;
QXmlStreamAttributes attributes = xml.attributes();
for (int i = 0; i < attributes.size(); ++i) {
QStandardItem *attributeItem = new QStandardItem(attributes.at(i).name().toString());
attributeItem->setData(attributes.at(i).value().toString(), Qt::UserRole);
item->appendRow(attributeItem);
}
} else if (token == QXmlStreamReader::EndElement) {
parentItem = parentItem->parent();
} else if (token == QXmlStreamReader::Characters) {
QString text = xml.text().toString().trimmed();
if (!text.isEmpty()) {
QStandardItem *textItem = new QStandardItem(text);
parentItem->appendRow(textItem);
}
}
}
file.close();
```
以上代码将XML文件中的每个元素作为一个`QStandardItem`,元素的属性作为子节点添加到元素节点下,元素的文本内容作为元素节点的子节点添加到元素节点下。最终得到的`QStandardItemModel`可用于在`QTreeView`等控件中显示XML数据。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)