Question

I have an XML file with the following format

<Objects>
    <Object>
        <Id>1</Id>
        <Name>Head</Name>
    </object>
    <Object>
        <Id>2</Id>
        <Name>Right Hand</Name>
    </object>
    <Object>
        <Id>3</Id>
        <Name>Left Hand</Name>
    </object>
    <Object>
        <Id>4</Id>
        <Name>Right hand</Name>
    </object>
    <Object>
        <Id>5</Id>
        <Name>Cup</Name>
    </object>
    <Object>
        <Id>6</Id>
        <Name>Book</Name>
    </object>
</Objects>

And I want to use a loop to access my file object by object with the following ways:

xml_node nodeObjects = doc.child("Objects").child("Object");

    for(xml_node_iterator it = nodeObjects.begin(); it != nodeObjects.end(); ++it)
    {
        cout<<"Name = "<<it->child_value("Name")<<endl;
    }

and also:

xml_node nodeObjects = doc.child("Objects");
for(xml_node nodeObject = nodeObjects.first_child(); nodeObject; nodeObject = nodeObject.next_sibling())
    {
        numOfObjects += 1;
        const char *id = nodeObject.child_value("Id");
        const char *name = nodeObject.child_value("Name");

        //cout<<"ID = "<<id<<" Name = "<<name<<endl;
        //cout<<nodeObjects.next_sibling("Object").child_value("Id")<<endl;;

    }

And finally:

xml_node nodeObjects = doc.child("Objects");
for(xml_node nodeObjects: nodeObjects.children("Object"))
    {
    }

While the first two methods did not print the expected results (only the first iteration works), the compiler says that third method is a syntax error!

Any help!

Was it helpful?

Solution

  1. Your XML file is malformed - end tag names should match start tags, comparison is case-sensitive. Remember to always check whether the document loaded successfully by checking xml_document::load_file return value. As it is right now, the parsing probably fails and you get an empty document (or rather a portion of the document up to the first error, i.e. just the first Object).

  2. First loop iterates through children of nodeObjects; for it to work, nodeObjects should refer to Objects tag, not its first Object child.

  3. Second and third loops look fine - third loop uses a C++11 feature and as such won't work on compilers that don't support it yet.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top