• V
 

转换到/从 XML

问题

你想在 XML 字符串和它所表示的 JavaScript 对象之间转换一个消息属性。

解决方案

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

示例

[{"id":"1b546d47.9474e3","type":"inject","z":"64133d39.bb0394","name":"XML 字符串","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":"对象","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 对象,这样在反向馈送时更容易理解。