如何读取root元素不是命名类型的xsd文件

时间:2016-01-16 06:15:07

标签: c++ xml xsd xerces

我有一个XML和XSD文件。如果XSD文件将根XML元素定义为命名complexType,我可以使用Xerces读取XML,但是我试图弄清楚如果XSD中的根项不是命名类型,如何读取文件。这是我的文件:

XML文件

<?xml version="1.0"?>
<x:books xmlns:x="urn:BookStore"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="urn:BookStore books.xsd">

   <book id="bk001">
      <author>Writer</author>
      <title>The First Book</title>
      <genre>Fiction</genre>
      <price>44.95</price>
      <pub_date>2000-10-01</pub_date>
      <review>An amazing story of nothing.</review>
   </book>

   <book id="bk002">
      <author>Poet</author>
      <title>The Poet's First Poem</title>
      <genre>Poem</genre>
      <price>24.95</price>
      <pub_date>2001-10-01</pub_date>
      <review>Least poetic poems.</review>
   </book>
</x:books>

XSD文件:

<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema"
            targetNamespace="urn:BookStore"
            xmlns:bks="urn:BookStore">

    <xsd:complexType name="BookForm">
        <xsd:sequence>
          <xsd:element name="author"   type="xsd:string"/>
          <xsd:element name="title"    type="xsd:string"/>
          <xsd:element name="genre"    type="xsd:string"/>
          <xsd:element name="price"    type="xsd:float" />
          <xsd:element name="pub_date" type="xsd:date" />
          <xsd:element name="review"   type="xsd:string"/>
        </xsd:sequence>
        <xsd:attribute name="id"   type="xsd:string"/>
  </xsd:complexType>        

  <xsd:element name="books">  <!-- not mapped to named typed! -->
      <xsd:complexType >
        <xsd:sequence>
          <xsd:element name="book" 
                      type="bks:BookForm" 
                      minOccurs="0" 
                      maxOccurs="unbounded"/>
          </xsd:sequence>
      </xsd:complexType>
  </xsd:element>
</xsd:schema>

阅读图书馆(只读两个字段)

#include <iostream>
#include "books.h"

using namespace std;
using namespace BookStore;

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);

    try {

        // what do I do here since BooksForm is not defined now and XSD file
        // doesn't map it to the root element of XML?
        auto_ptr<BooksForm> bookBank (books( "books.xml" ));

        for (BooksForm::book_const_iterator i = (bookBank->book().begin());
             i != bookBank->book().end();
             ++i)
        {
            cout << "Author is '" << i->author() << "'' " << endl;
            cout << "Title is '" << i->title() << "'' " << endl;

            cout << endl;
        }

    }
    catch (const xml_schema::exception& e)
    {
      cerr << e << endl;
      return 1;
    }

    return a.exec();
}

因此,如果XSD文件的格式与此post相同,则此代码有效,但我想知道如果XSD文件采用上述格式,我该如何读取XML。我需要在这个小型演示中执行此操作,以便我可以在另一个更大,更复杂的XML文件中解决类似情况,这是给定的事情。

0 个答案:

没有答案