简体   繁体   English

Node.js NodeList到XML字符串

[英]Node.js NodeList to XML string

I have some XML data that I need to handle in Node.js. 我有一些XML数据需要在Node.js中处理。 I need to strip an envelope (SOAP) and then just return the payload/body och the envelope. 我需要剥离一个信封(SOAP),然后仅返回有效载荷/正文。

I get it as a DOM Document into my code and I can easily find the Body content and get that into a NodeList object. 我将其作为DOM文档放入代码中,并且可以轻松找到Body内容并将其放入NodeList对象中。

Now I'd like to return the NodeList as a "XML String" but I haven't been able to find any way of doing this... What I basically need is a XML.stringify() (same as JSON.stringify()) but there doesn't seem to be any such function. 现在,我想以“ XML字符串”的形式返回NodeList,但是我找不到任何可以执行此操作的方法。我基本上需要的是XML.stringify()(与JSON.stringify( )),但似乎没有任何此类功能。

I've tried to write a "stringify()" myself but as there are attributes and namespaces in the XML it becomes very tricky... 我尝试自己编写一个“ stringify()”,但是由于XML中有属性和名称空间,因此变得非常棘手。

This might help you out. 这可能会帮助您。

function nodeListToString(nodeList){
    return [].slice.call(nodeList).reduce((str, x) =>{
        return str+=x.outerHTML;
    }, '');
}

calling Array.prototype.slice.call() on a NodeList object converts it to an array, we can then use the arrays reduce method. 在NodeList对象上调用Array.prototype.slice.call()会将其转换为数组,然后可以使用数组reduce方法。 reduce then iterates over everything in the array transforming it to the desired formt, read up on it here . 减少然后迭代数组中的所有内容,将其转换为所需的格式, 请在此处继续阅读

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

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