简体   繁体   English

如何在Node JS API中处理多个不同格式的XML有效负载

[英]How to handle multiple different format xml payloads in the node js api

I have to accept different types of xml formats in the node api, based on the value that is defined need to perform respective operations. 我必须根据需要执行相应操作定义的值,在节点api中接受不同类型的xml格式。

Here is the code which I'm trying: 这是我正在尝试的代码:

var xmlparser = require('express-xml-bodyparser');
    app.post('/xmlparser',xmlparser({trim: false, explicitArray: false}),function(request,reply){
    var data = JSON.stringify(request.body);
    var arr_data =JSON.parse(data);
    //code to access and display values from the xml

    console.log("xml 1:"+arr_data['ps0:tfg']['ps0:header']['ps1:messageid']);
    console.log("xml 2:"+arr_data['ps1:hls']['ps1:header']['ps1:messageid']);
})

Here are the 2 different xml, that takes as an input. 这是输入的2个不同的xml。

xml 1:
        <?xml version="1.0" encoding="UTF-8"?>
    <ps0:TFG xmlns:ns0="http://www.google.com/LOGO/Common">
    <ps0:Header version="1.0" xmlns:ns1="http://www.google.com/LOGO/Common">
    <ps1:MessageId>MESSAGE001</ns1:MessageId>
    </ps0:Header>
    </ns0:TFG>

xml 2:    
    <?xml version="1.0" encoding="UTF-8"?>
    <ps0:HLS xmlns:ns0="http://www.google.com/LOGO/Common">
    <ps0:Header version="1.0" xmlns:ns1="http://www.google.com/LOGO/Common">
    <ps1:MessageId>MESSAGE001</ns1:MessageId>
    </ps0:Header>
    </ps0:HLS>

I'm accepting different formats with in the same code as mentioned above, if i pass xml 1, xml 1 printing fine. 如果我通过xml 1,则xml 1可以正常打印,因此我接受与上述代码相同的不同格式。 if i pass the xml 2 as input, execution stops at 1st console log as the index is not available. 如果我将xml 2作为输入传递,则由于索引不可用,执行将在第一控制台日志处停止。

How can we handle this condition? 我们如何处理这种情况?

To resolve this I need to keep some conditions, atleast if it is showing undefined then i can mark in the condition, problem code is not executing if index mismatches. 为了解决这个问题,我需要保留一些条件,如果至少显示未定义,那么我可以在条件中标记,如果索引不匹配,则问题代码不会执行。

Update: I have tried implementing try catch as well, but still no luck. 更新:我也尝试过实现try catch,但是还是没有运气。

The problem probably stems from the fact that both XML and Javascript/JSON are case-sensitive. 问题可能源于XML和Javascript / JSON都区分大小写的事实。

For example, 例如,

const c = { alpha: 42 };
console.log(c.alpha) // ---> 42
console.log(c.Alpha) // ---> undefined

Likewise, in XML <ns1:MESSAGEID> is not the same tag as <ns1:MessageId> . 同样,在XML中, <ns1:MESSAGEID><ns1:MessageId>是不同的标记。

It is possible that whatever package you're using to parse your XML is messing around with the case, but that seems highly unlikely to me - any package that does that would not be compliant with standards. 您用来解析XML的任何软件包都可能会弄乱这种情况,但是对我来说,这似乎极不可能-任何不符合标准的软件包。

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

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