Parsing XML Elements using TinyXML

Jon picture Jon · Jun 29, 2011 · Viewed 29.5k times · Source

UPDATE: Still not working :( I have updated the code portion to reflect what I currently have.

This should be a pretty easy question for people who have used TinyXML. I'm attempting to use TinyXML to parse through an XML document and pull out some values. I figured out how to add in the library yesterday, and I have successfully loaded the document (hey, it's a start).

I've been reading through the manual and I can't quite figure out how to pull out individual attributes. After Googling around, I haven't found an example of my specific example, so perhaps someone here who has used TinyXML can help out. Below is a slice of the XML, and where I have started to parse it.

XML:

<EGCs xmlns="http://tempuri.org/XMLSchema.xsd">
  <card type="EGC1">
    <offsets>
      [ ... ]
    </offsets>
  </card>

   <card type="EGC2">
    <offsets>
      [ ... ]
    </offsets>
  </card>
</EGCs>

Loading/parsing code:

TiXmlDocument doc("EGC_Cards.xml");
if(doc.LoadFile())
{
    TiXmlHandle hDoc(&doc);
    TiXmlElement* pElem;
    TiXmlHandle hRoot(0);
    pElem = hDoc.FirstChildElement().Element();
    if (!pElem) return false;
    hRoot = TiXmlHandle(pElem);

    //const char *attribval = hRoot.FirstChild("card").ToElement()->Attribute("card");
    pElem = hDoc.FirstChild("EGCs").Child("card", 1).ToElement();
    if(pElem)
    {
        const char* tmp = pElem->GetText();
        CComboBox *combo = (CComboBox*)GetDlgItem(IDC_EGC_CARD_TYPE);
        combo->AddString(tmp);
    }
}

I want to pull out each card "type" and save it to a string to put into a combobox. How do I access this attribute member?

Answer

Jon picture Jon · Jun 29, 2011

After a lot of playing around with the code, here is the solution! (With help from HERE)

TiXmlDocument doc("EGC_Cards.xml");
combo = (CComboBox*)GetDlgItem(IDC_EGC_CARD_TYPE);

if(doc.LoadFile())
{
    TiXmlHandle hDoc(&doc);
    TiXmlElement *pRoot, *pParm;
    pRoot = doc.FirstChildElement("EGCs");
    if(pRoot)
    {
        pParm = pRoot->FirstChildElement("card");
        int i = 0; // for sorting the entries
        while(pParm)
        {
            combo->InsertString(i, pParm->Attribute("type"));
            pParm = pParm->NextSiblingElement("card");
            i++;
        }
    }
}
else 
{
    AfxMessageBox("Could not load XML File.");
    return false;
}