【问题标题】:how to get these XML elements with libxml2?如何使用 libxml2 获取这些 XML 元素?
【发布时间】:2010-11-09 15:39:56
【问题描述】:

我有一个 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>

现在我用 for 循环抛出所有孩子:

for (pCurrentElement...) {

}

现在我想访问 throw pCurrentElement foo1 和 foo2 但我不知道如何。 我使用 LIBXML2

我可以通过以下方式获得 foo1:

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

但我现在不知道如何获取 foo2?

【问题讨论】:

    标签: xml libxml2


    【解决方案1】:

    默认情况下,libxml2 将文档中的空白解析为它自己的子节点。如果 foo1 和 foo2 前面有空格,则 foo1 将是 pCurrentElement-&gt;children-&gt;next,而 foo2 将是 pCurrentElement-&gt;children-&gt;next-&gt;next-&gt;next

    如果您禁用空格解析,使用 xmlKeepBlanksDefault(0)xmlReadDoc(..., XML_PARSE_NOBLANKS),则 foo1 将是 pCurrentElement-&gt;children,而 foo2 将是 pCurrentElement-&gt;children-&gt;next

    【讨论】:

    • 我忘记了默认情况下,libxml2 将文档中的空白解析为它自己的子节点。我已经相应地更新了我的答案。
    • @RemyLebeau-TeamB 感谢“无空白”选项。默认行为令人讨厌,我在文档中找不到它。 (顺便说一句,它在 Perl 模块中称为“no_blanks”)。
    【解决方案2】:

    使用xmlNextElementSibling。当应用于foo1 时,它会为您提供foo2

    或循环遍历所有子 while (child-&gt;next) 并仅处理给定 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)
      

      自然而然

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

      【讨论】:

      • hm 问题是,然后我总是得到内容'\n'
      • pChildElement->next->children->content 怎么样?
      • @murtek:那是因为 libxml2 也将空格解析为节点,您没有考虑到这一点。请参阅我的其他答案。
      猜你喜欢
      • 2011-12-17
      • 1970-01-01
      • 2019-03-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-02-19
      • 1970-01-01
      相关资源
      最近更新 更多