【发布时间】:2014-01-04 15:39:04
【问题描述】:
我正在使用 libxml 的 HTML 解析器来创建一个 html 文档的 dom 树。 libxml 将每个节点的文本内容作为整体字符串(节点)提供,但我的要求是在空格处进一步拆分每个文本节点并创建尽可能多的单词节点。到目前为止,我还没有从 libxml 中找到任何选项,所以我创建了一个 cpu 昂贵的逻辑来分割文本节点。下面是递归方法的一部分。
void parse(xmlNodePtr cur, El*& parent) {
if (!cur) {
return;
}
string tagName = (const char*) cur->name;
string content = node_text(cur); // function defined below
Element* el = new Element(tagName, content);
parent->childs.push_back(el);
size_t pos;
string text;
cur = cur->children;
while (cur != NULL) {
if (xmlNodeIsText(cur) && (pos = node_text_find(cur, text, " ")) != string::npos) {
string first = text.substr(0, pos);
string second = text.substr(pos + 1);
El *el1 = new Element("text", first);
el->childs.push_back(el1);
El *el2 = new Element("text", " ");
el->childs.push_back(el2);
xmlNodeSetContent(cur, BAD_CAST second.c_str());
continue;
}
parse(cur, el);
cur = cur->next;
}
}
string node_text(xmlNodePtr cur) {
string content;
if (xmlNodeIsText(cur)) {
xmlChar *buf = xmlNodeGetContent(cur);
content = (const char*) buf;
}
return content;
}
size_t node_text_find(xmlNodePtr cur, string& text, string what){
text = node_text(cur);
return text.find_first_of(what);
}
上述代码的问题是它不适用于像中文这样的一些 UTF 字符串,而且这段代码在整个解析过程中增加了时间。
任何人都可以提出更好的方法,提前谢谢!
【问题讨论】: