ZBLOG

error: no member named 'text' in 'QDomNode'

抱歉给你带来了困惑,QDomNode 确实没有直接的 text() 方法。你需要首先将其转换为 QDomElement,然后再调用 text() 方法。以下是修正后的代码示例:

  1. #include <QCoreApplication>
  2. #include <QFile>
  3. #include <QDomDocument>
  4. #include <QString>
  5. #include <QDebug>
  6. void parseXml(const QString &xmlContent) {
  7. QDomDocument document;
  8. // 设置XML内容
  9. if (!document.setContent(xmlContent)) {
  10. qDebug() << "Failed to parse XML.";
  11. return;
  12. }
  13. // 获取根元素
  14. QDomElement root = document.documentElement();
  15. // 打印根元素名称(可选)
  16. qDebug() << "Root element:" << root.tagName();
  17. // 查找 CmdType 和 SN 元素(可选)
  18. QDomNodeList cmdTypeList = root.elementsByTagName("CmdType");
  19. QDomNodeList snList = root.elementsByTagName("SN");
  20. if (!cmdTypeList.isEmpty()) {
  21. QString cmdType = cmdTypeList.at(0).toElement().text();
  22. qDebug() << "CmdType:" << cmdType;
  23. }
  24. if (!snList.isEmpty()) {
  25. QString sn = snList.at(0).toElement().text();
  26. qDebug() << "SN:" << sn;
  27. }
  28. // 处理 Item 元素
  29. QDomNodeList itemList = root.elementsByTagName("Item");
  30. for (int i = 0; i < itemList.size(); ++i) {
  31. QDomElement itemElement = itemList.at(i).toElement();
  32. // 使用 toElement 来获取 Id 节点并读取文本
  33. QDomNode idNode = itemElement.firstChildElement("Id");
  34. if (!idNode.isNull()) {
  35. QString id = idNode.toElement().text(); // 修正:将 idNode 转换为 QDomElement
  36. qDebug() << "Item Id:" << id;
  37. }
  38. }
  39. }
  40. int main(int argc, char *argv[]) {
  41. QCoreApplication a(argc, argv);
  42. QString xmlData =
  43. "<?xml version=\"1.0\" encoding=\"GB2312\" standalone=\"yes\"?>"
  44. "<Notify>"
  45. "<CmdType>HotWordUpdate</CmdType>"
  46. "<SN>5</SN>"
  47. "<Item>"
  48. "<Id>1</Id>"
  49. "</Item>"
  50. "<Item>"
  51. "<Id>2</Id>"
  52. "</Item>"
  53. "<Item>"
  54. "<Id>3</Id>"
  55. "</Item>"
  56. "<Item>"
  57. "<Id>4</Id>"
  58. "</Item>"
  59. "</Notify>";
  60. parseXml(xmlData);
  61. return a.exec();
  62. }

更改说明:

  • 在处理每个 Item 时,将 idNode 转换为 QDomElement 以便调用其 text() 方法。原来的错误是在尝试在 QDomNode 上直接使用了不存在的方法。

这样,你就可以正确地提取 XML 中各个元素的文本内容了。如果有其他问题,请随时告诉我!


内容由零声教学AI助手提供,问题来源于学员提问

本站部分文章来源于网络,版权归原作者所有,如有侵权请联系站长删除。
转载请注明出处:https://golang.0voice.com/?id=20364

分享:
扫描分享到社交APP
上一篇
下一篇
发表列表
游客 游客
此处应有掌声~
评论列表

还没有评论,快来说点什么吧~

联系我们

在线咨询: 点击这里给我发消息

微信号:3007537140

上班时间: 10:30-22:30

关注我们
x

注册

已经有帐号?