0

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?

1 Answers1

2

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.

andy.holmes
  • 3,383
  • 17
  • 28
  • So I didn't miss anything. That's sad :( I've accepted your answer, but I don't think I'll follow your advice :) That module just feels a little… flaky. I'll go on with my current hack which calls out to a small Python script which reads the XML and emits a simple JSON with the relevant subset. –  Nov 16 '19 at 11:19
  • Well, it's worth pointing out everything you can do in GJS is with an introspected C library. So you could write a simple library, possibly based on the `g_markup_*` functions and generate GIR for it. Unfortunately until someone that encounters the lack of XML parser does this, there will continue to be no good alternative. – andy.holmes Nov 17 '19 at 19:10
  • I'm not familiar with Gobject and I don't particularly enjoy writing C, so I'm afraid that's well out of scope for what's a simple search provider extension :) –  Nov 18 '19 at 09:13