我目前正在努力构建一个应从解析HTML5(node-html5-parser
)中获取输入对象的函数,并且我需要处理所有标签和子标签,以及它们的内容以输出字符串xml。我遇到的问题是如何获取递归函数(或任何函数)以正确维护HTML5标记顺序并输出内容。
示例:
<div><span>My Content</span></div>
使用node-html5-parser解析时,我得到以下信息:
rootElem {
childNodes: [
{
tagName: 'div',
childNodes: [
{
tagName: 'span',
childNodes: [
{
rawText: 'My Content'
}
],
}
]
}
]
}
我以为可以使用简单的DFS递归算法来构建字符串,但是我无法使其正常工作。
const DOMRootObj = parse(this.htmlStr);
const processedData = this.processContent(DOMRootObj);
processContent(root: any): string {
if (root && !root.childNodes.length) {
return root.rawText;
} else {
for (const childNode of root.childNodes) {
const str = this.processContent(childNode);
const { tagName } = childNode;
if (tagName) {
this.outputStr += `<${tagName}>${str}</${tagName}>`;
}
}
}
}
由parse()函数解析的HTML :(对象如上)
<div><span>My Content</span></div>
这最终输出:
<span>undefined</span><div>undefined</div>
但它应该输出:
<div><span>My Content</span></div>
不确定您希望使用哪种XML格式,但是递归调用并不难实现:
几天来,浏览器内部出现了类似的问题。我想遍历dom树并在节点上执行具有给定参数的函数。就我而言,我想重新分配元素ID(如果有)。这就是为什么该函数命名为nodeinit的原因。无论如何