Menu

Howto: read "text" data

Lynn Allan
2002-01-30
2002-02-01
  • Lynn Allan

    Lynn Allan - 2002-01-30

    Hi Lee,

    I'm making progress, but now I'm baffled on how to access the "text" data.  The code below walks through the todo items, and prints the attribute values for "distance" and "priority".  However, I'm unclear how to "read" the "text" data for the element/item.  How do I address the "Go to the toy store", "Do Bills", and "Look for the Evil Dinosaurs!" so I can print it out?

    // Walk all the elements in a node.
    count = 0;
    element = todoElement->FirstChildElement();
    while (element != 0) {
      count++;
      printf("Type: %d  Priority: %s  Distance: %s\n",
          element->Type(),
          (element->Attribute("priority"))->c_str(),
          (element->Attribute("distance"))->c_str());
      element = element->NextSiblingElement();
    }

    Regards,
    Lynn Allan

     
    • Lee Thomason

      Lee Thomason - 2002-01-31

      TinyXml differs from some other APIs on this one. It's a somewhat subtle question.

      Text elements (TiXmlText) are nodes in the DOM tree like any other node. An element that contains text does not have any "Text" method to get it. You have to walk down to the child node, verify that it is a Text element, and get the Value() of that element. The value is the text of the TiXmlText.

      In this snippet:

      <ToDo>
      <Item priority="2" distance="close"> Go to the
      <bold>Toy store!
      </bold>
      ..etc

      The first child of the "ToDo" element is the "Item" element.
      The first child of the "Item" element is a Text node, which has the Value "Go to the"
      The sibling of the Text node is the "bold" element.

      lee

       
    • Lynn Allan

      Lynn Allan - 2002-01-31

      Thanks again for your patience with this newbie.  I changed the code to:

      // Walk all the elements in a node.
      element = todoElement->FirstChildElement();
      TiXmlText* text;
      while (element != 0) {
        text = (element->FirstChild())->ToText();
        printf("Pri: %s Distance: %s  Value:<%s>\n",
          (element->Attribute("priority"))->c_str(),
          (element->Attribute("distance"))->c_str(),
          (text->Value()).c_str());
        element = element->NextSiblingElement();
      }

       
      • Lee Thomason

        Lee Thomason - 2002-02-01

        No problem! It's a common issue, which needs to at the very least be documented better.

         

Log in to post a comment.