Parse XSD with QXmlStreamReader

531 Views Asked by At

I need to process some XSD for performing operations, and I need to process them as normal XML files. I want to take every element of the XSD and process them (for example by printing them and their attributes).

This is a little sample:

<?xml version="1.0" encoding="utf-8" ?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
  <xs:element name="name" type="xs:string"/>
</xs:schema>

I've tried to follow this post for retrieving data, but without success. This is my piece of code

void XSDReader::getStructure() const {
  QFile xsdFile(m_filePath.string().c_str());
  if (!xsdFile.open(QFile::ReadOnly | QFile::Text)) {
    throw Exception("Cannot read file " + m_filePath.string() + ". Error is: " + xsdFile.errorString().toStdString());
  }
  QXmlStreamReader reader(&xsdFile);
  std::stringstream ss;
  while (reader.readNextStartElement())
  {
    ss << "Found tag: " << reader.name().toString().toStdString() << "text: " << reader.text().toString().toStdString() << "token: " << reader.tokenString().toStdString();
    for (auto& attribute : reader.attributes())
    {
      ss << "attribute name: " << attribute.name().toString().toStdString() << ", attribute value: " << attribute.value().toString().toStdString();
    }
    reader.readNext();
    ss << "tag value:" << reader.text().toString().toStdString();
    reader.skipCurrentElement();
  }
  auto s = ss.str();
}

The string s after the processing is:

Found tag: schematext: token: StartElementtag value:

It does not contain anything regarding xs:string or its attributes.

How can I process correctly the XSD in order to print all of its data?

1

There are 1 best solutions below

3
kimbert On

I want to take every element of the XSD and process them (for example by printing them and their attributes).

An XML Schema has a complex structure which is difficult to handle if you treat the XSDs as XML documents. If you try anyway, you are quite likely to get it wrong.

Code libraries exist which will load an XSD (or a set of XSDs) into an in-memory model. Those libraries were written by experts who understand XML Schema in detail. But unfortunately, C++ is not well served with tools for handling XSDs, as indicated by this thread: XML Schema to C++ Classes

I have done a lot of XSD processing in Java using the EMF model. It is a fully-featured set of libraries and supports the entire XSD specification. There is a learning curve, but that will be true whatever technology you use; the XSD data model is complex.

You may say '...but my XSDs are simple'. If so, feel free to go ahead with your XML-based approach. But it is likely to produce a fragile solution which will not be easy to maintain.