• V
 

XMLの相互変換

課題

メッセージプロパティをXML文字列に変換したり、JavaScriptのオブジェクトに変換したりしたい。

解決

XML ノードを使用して、それぞれ2つのフォーマットを変換します。

[{"id":"1b546d47.9474e3","type":"inject","z":"64133d39.bb0394","name":"XML String","topic":"","payload":"{\"a\":1}","payloadType":"str","repeat":"","crontab":"","once":false,"onceDelay":0.1,"x":100,"y":260,"wires":[["d72b2bfd.77d068"]]},{"id":"1adf407d.6c4fe","type":"debug","z":"64133d39.bb0394","name":"","active":true,"tosidebar":true,"console":false,"tostatus":false,"complete":"false","x":590,"y":260,"wires":[]},{"id":"46638890.8ae758","type":"inject","z":"64133d39.bb0394","name":"Object","topic":"","payload":"{\"note\":{\"$\":{\"priority\":\"high\"},\"to\":[\"Nick\"],\"from\":[\"Dave\"],\"heading\":[\"Reminder\"],\"body\":[\"Update the website\"]}}","payloadType":"json","repeat":"","crontab":"","once":false,"onceDelay":0.1,"x":90,"y":300,"wires":[["dae1d291.de0d2"]]},{"id":"6fefca67.3669e4","type":"debug","z":"64133d39.bb0394","name":"","active":true,"tosidebar":true,"console":false,"tostatus":false,"complete":"false","x":430,"y":300,"wires":[]},{"id":"d72b2bfd.77d068","type":"template","z":"64133d39.bb0394","name":"","field":"payload","fieldType":"msg","format":"text","syntax":"plain","template":"<note priority=\"high\">\n  <to>Nick</to>\n  <from>Dave</from>\n  <heading>Reminder</heading>\n  <body>Update the website</body>\n</note>","output":"str","x":280,"y":260,"wires":[["1746464a.87aa4a"]]},{"id":"1746464a.87aa4a","type":"xml","z":"64133d39.bb0394","name":"","property":"payload","attr":"","chr":"","x":430,"y":260,"wires":[["1adf407d.6c4fe"]]},{"id":"dae1d291.de0d2","type":"xml","z":"64133d39.bb0394","name":"","property":"payload","attr":"","chr":"","x":250,"y":300,"wires":[["6fefca67.3669e4"]]}]

議論

例では、最初のフローが次のようなXML文字列を生成します:

<note priority="high">
  <to>Nick</to>
  <from>Dave</from>
  <heading>Reminder</heading>
  <body>Update the website</body>
</note>

そして、XML ノードはそれを等価なJavaScriptオブジェクトに変換します:

{
    "note": {
        "$": {
            "priority":"high"
        },
        "to": ["Nick"],
        "from": ["Dave"],
        "heading": ["Reminder"],
        "body": ["Update the website"]
    }
}

<note> タグの下に $ 属性が追加されていることに注意してください。

2つめのフローは逆を行っており、オブジェクトをinjectしてXMLに変換します。

特定のXMLフォーマットで出力を得たい場合、XML にinjectしながら、 必要となるJavaScriptオブジェクトを見つけ出す方法が簡単です。