Home > other >  Parsing XML file in Julia
Parsing XML file in Julia

Time:01-16

I am trying to parse an XML file in Julia which starts like this (sorry I cannot share the entire file for data protection):

<?xml version="1.0" encoding="utf-8"?>
<Device Name="Bob; ID=Unknown" Sources="1" GainFactor="20" Filter ="1">
    <Channels>
    </Channels>
</Device>

...... and continues. I need to get the value of the GainFactor part of the root name. I have tried using LightXML and EzXML, but can only seem to parse things from the child roots <Channels> and so on. Please could someone suggest a way of getting the info from the root part <Device....>. Thank you in advance, I am new to Julia! I've tried something like:

using EzXML

xdoc = readxml(FILE_NAME)
xroot = root(xdoc) 

for i in eachelement(xroot)
    println(i)
end

CodePudding user response:

Thanks for the sample XML. It would have been nice to make the sample XML a complete XML with appropriate closing tags. In any case, playing around with it, the following does the OP's request:

gfactor = nothing
for attr in eachattribute(xroot)
    if nodename(attr)=="GainFactor"
        gfactor = tryparse(Int, nodecontent(attr))
    end
end
if isnothing(gfactor)  # could not parse/find gfactor
    gfactor = 10 # some default value or error
end
  • Related