首页 > 解决方案 > QXMLStreamReader 无法读取属性

问题描述

我想解析以下xml(它是一个xsd):

<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" elementFormDefault="qualified" attributeFormDefault="unqualified">
  <xs:element name = "elementName">
    <xs:simpleType>
      <xs:restriction base = "xs:string">
      </xs:restriction>
    </xs:simpleType>
  </xs:element>
</xs:schema>

在某些时候,我调用以下方法,该方法应读取的base属性restriction

void String::getFromBase() const {
  QXMLStreamReader m_node; // in true code it's a class member already initialized
  m_node.readNextStartElement();
  auto name = stripNamespace(m_node.name().toString()); // convert xs:restriction to restriction
  if (name != "restriction") {
    throw Exception("Restriction is not found when reading string data");
  }
  bool hasBase{false};
  auto x = m_node.attributes().size(); // x is zero but it should be one
  for (const auto& it : m_node.attributes()) {
    auto attrName = stripNamespace(it.name().toString());
    if (attrName == "base") {
      hasBase = true;
      break;
    }
  }
  if (!hasBase) {
    throw Exception("Restriction needs 'base' attribute");
  }
  auto attribute = stripNamespace(m_node.attributes().value(BaseLabel).toString());
  if (attribute == "string") {
    int i = 0;
  }
}

该方法检查QXMLStreamReaderis中的实际元素restriction,并且该检查通过,但随后 的大小attributes()为零,因此阅读器没有找到任何属性。因为我restriction在测试 XSD 中只有一个,所以属性应该在那里。如何base正确读取属性值?

标签: c++xmlqtxsdqxmlstreamreader

解决方案


推荐阅读