简体   繁体   English

如何使用libxml2获取这些XML元素?

[英]how to get these XML elements with libxml2?

i have a XML structure: 我有一个XML结构:

<?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循环:

for (pCurrentElement...) {

}

now i want to access throw pCurrentElement the foo1 and foo2 but i dont know how. 现在我想访问将foo1和foo2抛出pCurrentElement,但是我不知道如何。 i use LIBXML2 我使用LIBXML2

i can get foo1 with: 我可以通过以下方式获取foo1:

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

but i dont know how to get foo2 now? 但我现在不知道如何获取foo2?

By default, libxml2 parses whitespace within the document into its own child nodes. 默认情况下,libxml2将文档中的空格解析为自己的子节点。 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 . 如果foo1和foo2前面有空格,则foo1将为pCurrentElement->children->next ,而foo2将为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. 如果禁用空白解析,请使用xmlKeepBlanksDefault(0)xmlReadDoc(..., XML_PARSE_NOBLANKS) ,则foo1将是pCurrentElement->children而foo2将是pCurrentElement->children->next

Use xmlNextElementSibling . 使用xmlNextElementSibling When applied to foo1 , it gives you foo2 . 当应用于foo1 ,它将为您提供foo2

Or loop through all the children while (child->next) and process only nodes of given type . 或循环遍历所有while (child->next)并仅处理给定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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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