[xml] iterating through an XML document?



Hi,

using one of the examples i wrote an XML file as "out.xml":

<?xml version="1.0" encoding="UTF-8"?>
<root>
  <node1>content of node 1</node1>
  <node2/>
  <node3 attribute="yes" foo="bar">this node has attributes</node3>
  <node4>other way to create content (which is also a node)</node4>
  <node5>
    <node51 odd="no"/>
    <node52 odd="yes"/>
    <node53 odd="no"/>
  </node5>
  <node6>
    <node61 odd="no"/>
    <node62 odd="yes"/>
    <node63 odd="no"/>
  </node6>
</root>

Now i wrote some code to read this file into memory and get its root node
and i'd like to output the document recursively.  I want to do this to
get known to libxml2 and on how to iterate through a document:


void show(xmlNode* node, int indent) {
  xmlNode* n;
  int i;

  for(n = node; n; n = n->next) {
    if(n->type == XML_ELEMENT_NODE) {
      for(i = 0; i < indent; i++) printf(" ");
      printf("<%s> <%s>\n", n->name, xmlIsBlankNode(n) ? "<empty>" : 
xmlNodeGetContent(n));
      show(n->children, indent+2);
    }
    if(n->type == XML_ATTRIBUTE_NODE) {
      for(i = 0; i < indent; i++) printf(" ");
      printf("<%s>+<%s>\n", n->name, xmlIsBlankNode(n) ? "<empty>" : 
xmlNodeGetContent(n));
    }
  }
}


It does not exactly do what i want, i can't see any attributes like foo="bar"
or others.  Also, for nodes that do not have text, some empty lines are
printed, not the string "<empty>" as i want it to be.


I hope i don't mix up names, i'm not sure when to use attribute and
when property.


For using libxml2 in an own program i'd like to know how to:
- test if a node has a content or not
- test what attributes (or properties?) a node has

It would be great if anybody could give me a hint on how to do this.


Best regards,
Torsten.



[Date Prev][Date Next]   [Thread Prev][Thread Next]   [Thread Index] [Date Index] [Author Index]