2017-08-09 8 views
1

私はnode.jsを初めて利用しており、XMLを解析する必要があります。 jsでは、私はちょうどDOMParserを使用し、私が望む値を得るためにgetElementsByTagNameを使用します。私はちょうどノードに切り替えて、xml2js(代替案を検討する意思がある)を使用しています。私は、私が探しているものを得るための応答を解析する方法を理解することができませんでした。以下xml2jsで解析する

コード:私の関数の出力ここで

<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:int=\"realURLHere"> 
    <soapenv:Header/> 
    <soapenv:Body> 
     <int:readResponse> 
     <response> 
      <request>?</request> 
      <cust> 
       <fName>?</fName> 
      </cust> 
     </response> 
     </int:readResponse> 
    </soapenv:Body> 
</soapenv:Envelope> 

されています:

{ 'soapenv:Envelope': 
    { '$': 
     { 'xmlns:soapenv': 'http://schemas.xmlsoap.org/soap/envelope/', 
     'xmlns:int': 'realURLHere' }, 
    'soapenv:Body': [ [Object] ] 
    } 
} 

私はここに

function parseBody(body){ 
    var parseString = require('xml2js').parseString; 
    var xml = body 
    parseString(xml, function (err, result) { 
    console.dir(result); 
}); 

とは、私は関数に渡していたXMLです<cust>にある<fName>の値にアクセスしようとしましたが、運がありません。どんな助けもありがとう。ありがとう!

答えて

0

var custFName = result['soapenv:Envelope']['soapenv:Body'][0]['int:realURLHe‌​re'][0]['response'][‌​0]['cust'][0]['fName‌​'];

これは私の問題を解決しました。私の苦労は、すべてのことを配列にしたこの応答と関係していました。これを行う簡単なやり方があれば、私に教えてください。しかし今のところ、これはうまくいった。

+0

以下の回答を試してみてくださいを使用してアクセスすることができます

{ "fname": "hello world" } 

をプリントアウトし、この

const transform = require('camaro') const xml = ' <soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:int=\"realURLHere"> <soapenv:Header/> <soapenv:Body> <int:readResponse> <response> <request>?</request> <cust> <fName>hello world</fName> </cust> </response> </int:readResponse> </soapenv:Body> </soapenv:Envelope> ' const template = { fname: '//cust/fName' } const result = transform(xml, template) console.log(JSON.stringify(result, null, 2)) 

をお試しください –

0

あなたはresult.fname

関連する問題