如何使用node.js获取SOAP主体?

时间:2018-01-10 10:31:42

标签: javascript node.js soap

我的传入SOAP消息的格式如下:

const soap = `
<?xml version="1.0" encoding="UTF-8"?>
<env:Envelope xmlns:env="http://www.w3.org/2003/05/soap-envelope">
    <env:Header/>
    <env:Body property="def">
        <Root>
            <Abc attr="abc">123456</Abc>
        </Root>
    </env:Body>
</env:Envelope>
`;

我期望得到的是<env:Body>的内容不变:

<Root>
    <Abc attr="abc">123456</Abc>
</Root>

要提取身体,我使用简单的正则表达式:

function getSoapBody(xmlStr) {
    let soapBody = null;
    if (xmlStr) {
        const soapBodyRegex = /<env:Body>([\s\S]*)<\/env:Body>/im;
        const soapBodyRegexMatchResult = xmlStr.match(soapBodyRegex);
        soapBody = soapBodyRegexMatchResult[1];
    }
    return soapBody;
}

然而,当然,获取正则表达式的身体并不理想。

此外,我不想重新发明轮子,我正在寻找一个基本上getSoapBody的解决方案(甚至是npm包),无论使用什么前缀(如果前缀改变,上面的正则表达式会失败)或者如果有的话是可选属性等。

2 个答案:

答案 0 :(得分:2)

您可以使用xml2js解析:

var xml2js = require('xml2js');
var builder = new xml2js.Builder();

const soap = `
<?xml version="1.0" encoding="UTF-8"?>
<env:Envelope xmlns:env="http://www.w3.org/2003/05/soap-envelope">
    <env:Header/>
    <env:Body optional="abc">
        <Root>
            <Abc attr="1">123456</Abc>
        </Root>
    </env:Body>
</env:Envelope>
`;

var options = {explicitArray: false, tagNameProcessors: [xml2js.processors.stripPrefix] };

xml2js.parseString(soap, options, (err, result) => {
    if (err) {
        console.log('An error has occurred: ' + err);
        return;
    } 

    // Get the soap body object
    var soapBody = result.Envelope.Body;

    // Remove optional attribute(s) from <Body> element.
    if (soapBody.$) {
        delete soapBody.$;
    }

    // Get the body XML if needed
    var soapBodyXML = builder.buildObject(soapBody);

    console.log(soapBodyXML);
});

答案 1 :(得分:1)

我使用fast-xml-parser(https://www.npmjs.com/package/fast-xml-parser/v/2.9.0)通过使用以下选项来排除命名空间和前缀并确保属性位于节点“ attr”下来实现此目的:

async function stripBodyFromSoapEnvelope(inputBody){
    const xmlParser = require('fast-xml-parser');        
    let options = {
            attributeNamePrefix : '',
            attrNodeName: 'attr',
            ignoreNameSpace: true,
            ignoreAttributes: false
        };
    const soapenv = xmlParser.parse(inputBody,options);
    return(soapenv.Envelope.Body);
}

希望这会有所帮助。