• V
 

转换为/从 XML

问题

您希望在 XML 字符串和它所代表的 JavaScript 对象之间转换消息属性。

解决方案

XML 节点可用于在这两种格式之间进行转换。

示例

[{"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> 标签的属性是如何被添加到 note 对象的 $ 属性下的。

第二个流程执行相反操作,注入该对象并将其转换为 XML。

当需要特定的 XML 输出格式时,可以先将其注入 XML 节点,以查看在反向馈送时生成它所需的 JavaScript 对象,这会更容易。