This forum uses cookies
This forum makes use of cookies to store your login information if you are registered, and your last visit if you are not. Cookies are small text documents stored on your computer; the cookies set by this forum can only be used on this website and pose no security risk. Cookies on this forum also track the specific topics you have read and when you last read them. Please confirm that you accept these cookies being set.

Process XML Data
#1
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
Reply
#2
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)
Reply
#3
Works perfectly .. many thanks!
Reply


Forum Jump: