简体   繁体   中英

how to get these XML elements with libxml2?

i have a XML structure:

<?xml version="1.0" encoding="UTF-8" standalone="yes" ?>
<root>
<item>
    <foo1>1</foo1>
    <foo2>2</foo2>
</item>
<item>
    <foo1>3</foo1>
    <foo2>4</foo2>
</item>
</root>

now i go throw all children with a for loop:

for (pCurrentElement...) {

}

now i want to access throw pCurrentElement the foo1 and foo2 but i dont know how. i use LIBXML2

i can get foo1 with:

pChildElement = pCurrentElement->children->next;
pChildElement->children->content // foo1

but i dont know how to get foo2 now?

By default, libxml2 parses whitespace within the document into its own child nodes. If there is whitespace in front of foo1 and foo2, then foo1 will be pCurrentElement->children->next , and foo2 will be pCurrentElement->children->next->next->next .

If you disable whitespace parsing, using either xmlKeepBlanksDefault(0) or xmlReadDoc(..., XML_PARSE_NOBLANKS) , then foo1 will be pCurrentElement->children and foo2 will be pCurrentElement->children->next instead.

Use xmlNextElementSibling . When applied to foo1 , it gives you foo2 .

Or loop through all the children while (child->next) and process only nodes of given type .

pChildElement = pCurrentElement->children->next; //if this is pointing to <item>
pChildElement->children->content // foo1  // this is <item>->children->first element (which is foo1)

so naturally

pChildElement->children->next->content would be the next sibling of foo1, which is foo2

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM