【问题标题】:blank removal in xml using libxml2使用 libxml2 在 xml 中删除空白
【发布时间】:2012-09-05 09:55:35
【问题描述】:

我的 xml 文件为:

<Config>
    <tlvid id="2">
              <type>10</type>
              <Devid>001b00100000</Devid>
    </tlvid>

    <tlvid id="3">
             <sessionid>abcd123</sessionid>
    </tlvid>

解析xml文件的代码是:

xmlNode *cur_node = NULL,*sub_node = NULL;
xmlChar *key;

cur_node = a_node->xmlChildrenNode;
while(cur_node !=NULL) {

        if((!xmlStrcmp(cur_node->name,(const xmlChar*)"tlvid"))) {
            key = xmlGetProp(cur_node,(const xmlChar*)"id");
            printf("key: %s\n ",key);
            xmlFree(key);
            sub_node = cur_node->xmlChildrenNode;

            while(sub_node !=NULL) {

            key = xmlNodeGetContent(sub_node);
            printf("subkey: %s\n ",key);
            xmlFree(key);

            sub_node = sub_node->next;
            }
        }
     cur_node = cur_node->next;
}

输出为:

键:2

子项:

子键:10

子项:

子键:001b00100000

子项:

键:3

子项:

子项:abcd123

子项:

我已经尝试过 xmlKeepBlanksDefault(0);在while循环下添加以避免空白,但没有帮助。你能帮我删除这些空白吗?谢谢。

【问题讨论】:

  • 打印前不能检查key是否为空吗?
  • 感谢您的回复。是的,我已经检查过了,但仍然打印相同。在打印之前给出 if(key)。
  • 你应该检查一下if (strlen(key) != 0) 之类的,因为key 仍然是一个有效的指针。
  • 没有用。仍然是相同的输出。尝试打印 strlen(key),每个空格的值分别为 5、5、4、2。

标签: c xml-parsing libxml2


【解决方案1】:

通过检查xmlNodeIsText避免处理cur_node的文本子代:

for(sub_node = cur_node->xmlChildrenNode;
    sub_node != NULL;
    sub_node = sub_node->next)
{
    if(xmlNodeIsText(sub_node)) continue;
    …
}

作为跳过所有文本节点的替代方法,您可以使用xmlIsBlankNode 确保只跳过空白节点:

for(sub_node = cur_node->xmlChildrenNode;
    sub_node != NULL;
    sub_node = sub_node->next)
{
    if(xmlIsBlankNode(sub_node)) continue;
    …
}

如果&lt;tlvid&gt; 元素中直接有非空白文本,则这两个结果会有所不同。

阅读the manual for xmlKeepBlanksDefault 找出使解析器忽略这些空白节点所需的条件。显然,您需要一个验证解析器和一个合适的 DTD 才能产生效果。

【讨论】:

  • continue 需要一个 for(;;) 而不是 while(),否则循环变量不会被碰撞。
  • @wildplasser,你说得对,相应地编辑了答案。
  • 好吧,我正要评论 OP 的 BadStyle(恕我直言)。 for(;;) {} 循环更方便,if (...) continue; 跳过不需要的内容可避免额外的 {} 块+相关的缩进。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-01-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多