1

I'm new to libxml2 and started with an example, I don't understand why my sample code doesn't read some of the tags. I have my XML file in this way.

<ACCOUNTS>
<ACCOUNT NO="123">
<STATE>GA</STATE>
<NAME>John</NAME>
</ACCOUNT>
<ACCOUNT NO="123">
<STATE>GA</STATE>
<NAME>Burgess</NAME>
</ACCOUNT>
</ACCOUNTS>

Here is my sample code :

void getReference (xmlDocPtr doc, xmlNodePtr cur) {
    xmlChar *uri;
    xmlChar *value;
    cur = cur->xmlChildrenNode;
    while (cur != NULL) {
        if ((!xmlStrcmp(cur->name, (const xmlChar *)"ACCOUNT"))) {
            uri = xmlGetProp(cur,(const xmlChar*) "NO");
            printf("uri: %s\n", uri);
            xmlFree(uri);
        }
        cur = cur->next;
    }
    return;
}

When I debug I notice it goes to ACCOUNT tag for the first time and get the value and then move on to next ACCOUNT tag, ignoring STATE and NAME tags. What is wrong in this program and is this the correct approach?

0

1 Answer 1

3

First of all I'm not an expert on libxml2. However, you noticed that your code goes from the node account to the next node account. This is because the other nodes are under these account nodes. In order to get to these forgotten subnodes, you must descend into the subnodes hierarchy.

It's probably more understandable if you see it this way:

<ACCOUNTS>
  <ACCOUNT NO="123">
    <STATE>GA</STATE>
    <NAME>John</NAME>
  </ACCOUNT>
  <ACCOUNT NO="123">
    <STATE>GA</STATE>
    <NAME>Burgess</NAME>
  </ACCOUNT>
</ACCOUNTS>

As you can see, nodes state and name are under nodes account. So, instead of going to the next one, you must run over all children nodes under each one before.

Basically (as a simple patch or quick solution), inside your if statement, you must create a nested while with this:

subnode = cur->xmlChildrenNode;
while (subnode != NULL) {
    if ((!xmlStrcmp(subnode->name, (const xmlChar *)"STATE"))) {
        // more things...
    }
}

Hope this helps.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.