Logic Machine Forum
Process XML Data - Printable Version

+- Logic Machine Forum (https://forum.logicmachine.net)
+-- Forum: LogicMachine eco-system (https://forum.logicmachine.net/forumdisplay.php?fid=1)
+--- Forum: Scripting (https://forum.logicmachine.net/forumdisplay.php?fid=8)
+--- Thread: Process XML Data (/showthread.php?tid=5439)



Process XML Data - jamesng - 29.05.2024

Hi

I'm trying to process some XML data and extract the parameter values. For example, the UserID 1234 in the xml below.

xml =[[<?xml version="1.0" encoding="utf-8"?>
<Response>
<Name>Login</Name>
<Parameters>
<Parameter name="Status" dataType="int">0</Parameter>
<Parameter name="StatusMessage" dataType="string">Successful</Parameter>
<Parameter name="UserID" dataType="int">1234</Parameter>
<Parameter name="Firstname" dataType="string">James</Parameter>
<Parameter name="AllowR1XTill" dataType="string">2023-06-30</Parameter>
</Parameters>
</Response>]]


I gather I should be using the following to parse the XML but haven't come across an example of how to implement it. Has anyone done something similar?


require('lxp').new({
StartElement = starttag,
EndElement = endtag,
CharacterData = text,
}):parse(xml)

Many thanks in advance

Kind Regards
James


RE: Process XML Data - admin - 29.05.2024

Try this:
Code:
xml =[[<?xml version="1.0" encoding="utf-8"?>
<Response>
<Name>Login</Name>
<Parameters>
<Parameter name="Status" dataType="int">0</Parameter>
<Parameter name="StatusMessage" dataType="string">Successful</Parameter>
<Parameter name="UserID" dataType="int">1234</Parameter>
<Parameter name="Firstname" dataType="string">James</Parameter>
<Parameter name="AllowR1XTill" dataType="string">2023-06-30</Parameter>
</Parameters>
</Response>]]

parameters = {}

function starttag(parser, tag, attrs)
  if tag == 'Parameter' then
    name = attrs.name
  end
end

function text(parser, text)
  if name then
    parameters[ name ] = text:trim()
    name = nil
  end
end

require('lxp').new({
  StartElement = starttag,
  CharacterData = text,
}):parse(xml)

log(parameters)
log(parameters.UserID)



RE: Process XML Data - jamesng - 29.05.2024

Works perfectly .. many thanks!