Skip to content
Advertisement

Extract fields from a custom xml

Im making a script to extract fields from a XML, now i got this and i need to make it work, i was trying with 2 for and greps and i need a little help with this

JavaScript

i got this xml withs this fields

JavaScript

and i want a output like this for make more comparations:

JavaScript

Advertisement

Answer

there are many issues with the code.

  • General:
    • Indent your code, it makes it much simpler for you and others to debug and support the code.
    • When writing a script, do it almost line per line, and test every line. Add echo of your variables, …
    • Do not write a whole bunch of lines and then try to figure out why it does not work.
    • Ex. the very first line in extract() does not work. If you try extract() with just that one line, do not move forward, debug that first.
  • Prueba.xml:
    • You have a RecordStart, then another RecordStart, than a RecordStop. Did you forget the RecordStop for the first RecordStart?
    • I added test data because it is hard to debug with empty fields.
  • charge_files:
    • Does nothing else than check if the file exists. But fine.
    • No need for ‘;’ on the echo commands, or the XML assignment. Removed.
    • If the XML file is not present, your script will run regardless. I added an exit because the file needs to exist for the rest of the script.
  • extract:

    • You cannot use for to iterate on lines like you tried to do. For will iterate on every word. Use the while like I put in my code.
    • You need to loop on every line, look at my code. Your method with the grep Telegram would not differentiate between PC1’s Telegram lines and PC2’s Telegram lines.
    • The grep command returns the entire line. So if you grep on a word in a line, it will not return a portion of the line, it will return the entire line.
    • To extract parts of a line, you can use cut (like I did since your requirements are simple), awk, sed.
  • Assumptions:

    • the lines always contain the same information, in the same order.

So here is the XML file I used for my tests:

JavaScript

And here the script:

JavaScript

Which produced this output:

JavaScript
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement