how to get these XML elements with libxml2?

早过忘川 提交于 2019-12-12 01:59:21

问题


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?


回答1:


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.




回答2:


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.




回答3:


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


来源:https://stackoverflow.com/questions/4135496/how-to-get-these-xml-elements-with-libxml2

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!