繁体   English   中英

如何解析具有类似XML结构但在内容旁边带有自关闭标签的文件(而不是封闭内容)

[英]How do I parse a file with XML-like structure, but with self-closing tags next to content (instead of enclosing the content)

我有以下结构的文件。 它不是XML,但我需要以某种方式使它成为JSON。

因此, 虽然我希望文件看起来像这样:

<chapter>
<line> Some text which I want to grab. </line>
<line> Some more text which I want to grab. </line>
<line> Even more text which I want to grab. </line>
</chapter>

它的结构实际上是这样的:

<chapter>
<line /> Some text which I want to grab.
<line /> Some more text which I want to grab.
<line /> Even more text which I want to grab.
</chapter>

因此,每章的“行”仅位于自闭合行标签旁边。 你能推荐一种抓住这些的方法吗? 可能在javascript / nodejs中?

该格式是有效的XML,因此您可以使用常规XML技术(即DOMParser )来解析内容

但是,您只需要对行进行解析就比较聪明了-您想要找到每一行,并收集所有作为文本节点的同级节点(应该只是一个,但是我给出的代码没有做任何假设) )

您没有指定输出“结构”,但是这是可以使用的一种输出嵌套数组的方法-第一级是章节,每章中都有一个行数组

var xml = `<chapter>
<line /> Some text which I want to grab.
<line /> Some more text which I want to grab.
<line /> Even more text which I want to grab.
</chapter>`

var parser = new DOMParser();
var content = parser.parseFromString(xml, 'application/xml')
var chapters = content.getElementsByTagName('chapter');
var obj = [].reduce.call(chapters, function(result, chapter) {
    var lines = chapter.getElementsByTagName('line');
    result.push([].reduce.call(lines, function(result, line) {
        var text = '';
        for(var node = line.nextSibling; node && node.nodeType == 3; node = node.nextSibling) {
            text += node.nodeValue;
        }
        result.push(text);
        return result;
    }, []))
    return result;
}, []);
console.log(JSON.stringify(obj));

处理评论-首先是一些文档:

DOMParse文档

Array#reduce文档

Function#call文档

现在,在这段代码中解释[].reduce.call(array, fn)

[].reduce.callArray.prototype.reduce.call简写

getElementsByTagName返回一个HTMLCollection ...,它的行为类似于数组,但是它不是一个...有几种方法可以使一个HTMLCollection成为一个数组-最原始的:

var array = [];
for(var i = 0; i < collection.length; i++) {
    array[i] = collection[i];
}

要么

var array = Array.prototype.slice.call(collection);

或(ES2015 +)-除非您使用polyfill,否则在IE中不可用-请参阅文档

var array = Array.from(collection);

但是,在[].reduce上使用.call方法可以使第一个参数( this参数)可以迭代,而不仅是数组,因此就像使用array.reduce(fn)这样的array -这是一个将HTMLcollection视为数组的方式,无需中间变量

暂无
暂无

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

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