Ono
Ono

Reputation: 1357

tinyxml parsing xml file

I have a xml file like this:

<?xml version="1.0"?>

<ApplicationSettings>
    <BeamGeometry  
        Dimension="2"
        Type="fan"
        Shape="arc"
        LengthFocalPointToISOCenter="558"
        LengthISOCenterToDetector="394"
        LengthDetectorSeperation="0.98"
        LengthModuleSeperation="0.04"
        NumberModules="57" 
        NumberDetectorsPerModule="16" 
        NumberISOCenterShift="3.25" />
</ApplicationSettings>

And I'd like to use tinyxml retrieving all the values (such as 558) based on the entry name such as (LengthFocalPointToISOCenter). Here is my code, not successful yet.

int SetFanbeamGeometry(const char* filename)    
{   
    int ret = TRUE;

    TiXmlDocument doc("E:\\Projects\\iterativeRecon\\ProjectPackage\\ApplicationSettings\\ApplicationSettings.xml");

    int LengthFocalPointToISOCenter;

    if( doc.LoadFile())
    {

        TiXmlHandle hDoc(&doc);
        TiXmlElement *pRoot, *pParm;
        pRoot = doc.FirstChildElement("ApplicationSettings");
        if(pRoot)
        {
            pParm = pRoot->FirstChildElement("BeamGeometry");
            int i = 0; // for sorting the entries
            while(pParm)
            {
                pParm = pParm->NextSiblingElement("BeamGeometry");
                i++;
            }
        }
    }
    else
    {
        printf("Warning: ApplicationSettings is not loaded!");
        ret = FALSE;
    }

    return ret;
}

I am wondering how can I use tinyxml to do that? Sorry I am a first time user. and it looks confusing to me. Thanks.

Upvotes: 0

Views: 911

Answers (1)

Jonathan Potter
Jonathan Potter

Reputation: 37122

There's only one BeamGeometry child element in the snippet you've shown; the information you're trying to access are its attributes - they're not individual elements.

So you need something like this:

// ...
pParm = pRoot->FirstChildElement("BeamGeometry");
if (pParm)
{
    const char* pAttr = pParm->Attribute("LengthFocalPointToISOCenter");
    if (pAttr)
    {
        int iLengthFocalPointToISOCenter = strtoul(pAttr, NULL, 10);
        // do something with the value
    }
}

If you want to loop through all attributes, it's quite simple:

const TiXmlAttribute* pAttr = pParm->FirstAttribute();
while (pAttr)
{
    const char* name = pAttr->Name(); // attribute name
    const char* value = pAttr->Value(); // attribute value
    // do something
    pAttr = pAttr->Next();
}

Upvotes: 1

Related Questions