Search code examples
xmlgnome-shell-extensionsgjs

Parse XML in GJS?


How can I parse XML in GJS code? Specifically, in a gnome shell extension? I haven't found anything, and there doesn't seem to be a GJS XML library. Also, GJS doesn't appear to be compatible with nodejs, so I can't use xml-js or the like?

Am I missing something?


Solution

  • As far as I know, there is no introspected library (eg. gobject-introspection) in the GNOME platform for parsing XML at this time (October 2019).

    Assuming the XML is fairly straight forward, you should be able to do this with some existing pure JavaScript parser. I copy-pasted lines 15-220 from https://github.com/kawanet/from-xml/ 1 and this worked reasonable well for me.

    const GLib = imports.gi.GLib;
    const Gio = imports.gi.Gio;
    
    const ByteArray = imports.byteArray;
    
    // from-xml pasted or imported here
    
    let xmlText = GLib.file_get_contents('test.xml')[1];
    
    if (xmlText instanceof Uint8Array)
        xmlText = ByteArray.toString(xmlText);
    
    let xmlParsed = parseXML(xmlText);
    print(JSON.stringify(xmlParsed, null, 2));
    

    This XML in text.xml:

    <tag>
     <child/>
     <child attr="bar">text</child>
    </tag>
    

    Printed this to the console:

    {
      "f": [
        {
          "f": [
            {
              "f": [],
              "n": "child",
              "c": 1
            },
            {
              "f": [
                "text"
              ],
              "n": "child",
              "t": " attr=\"bar\""
            }
          ],
          "n": "tag"
        }
      ]
    }
    

    No doubt there are more comprehensive libraries available, or a bit of work could be applied to improve the situation.