[英]How do you get only XML elements and not whitespace with the javascript DOMParser?
So, I am trying to parse XML with javascript, but when I do this, any whitespace, likes spaces or newlines causes unwanted nodes in the resulting DOM or XMLDocument object:所以,我试图用 javascript 解析 XML,但是当我这样做时,任何空格,如空格或换行符都会导致生成的 DOM 或 XMLDocument 对象中出现不需要的节点:
//xml parsing example var xp = new DOMParser(); var test = "<program><event><i>6</i></event></program>"; var xenon = xp.parseFromString(test, "text/xml"); console.log(xenon.childNodes[0].childNodes.length); //prints 1 //adding newlines test = "<program>\\n<event>\\n<i>6</i></event></program>"; xenon = xp.parseFromString(test, "text/xml"); console.log(xenon.childNodes[0].childNodes.length); //prints 2
How do I parse the xml so that only elements, and not any whitespace are included as child nodes?如何解析 xml,以便仅包含元素而不包含任何空格作为子节点? I have looked up a "clean" method, but there should be a parser option for this.
我已经查找了一个“干净”的方法,但应该有一个解析器选项。
No There is no parse option.否 没有解析选项。 The parsing procedure sees that
'\\n'
should be text nodes so it creates them as text nodes.解析过程看到
'\\n'
应该是文本节点,因此将它们创建为文本节点。 What you need to do is that after the parsing, ignore those text node.您需要做的是解析后,忽略那些文本节点。 childNodes selects all the children including the text nodes ones, use children instead.
childNodes选择包括文本节点在内的所有子节点,请改用子节点。
children
return only element children. children
只返回元素孩子。 Or use querySelectorAll
like this:或者像这样使用
querySelectorAll
:
var elems = xenon.querySelectorAll("program > *");
console.log(elems.length); // outputs 1
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.