Search code examples
xpathxml-namespaceslibxml2vala

vala / libxml2 : how to query xpath with namespace ? (xpathRegisterNs?)


how do you register namespace on context with vala so that you can query "//someNamespace:tag" (and not only "//tag")

My starting point is : https://live.gnome.org/Vala/XmlSample

            Xml.Doc* doc = Parser.parse_file (path);
            if(doc==null) print("failed to read the .xml file\n");

            Context ctx = new Context(doc);
            if(ctx==null) print("failed to create the xpath context\n");

            Xml.XPath.Object* obj = ctx.eval_expression("/Example/Objects/Pet");
            if(obj==null) print("failed to evaluate xpath\n");

I guessed[*] how to "create" some namespace

Xml.Ns* ns = new Xml.Ns(null,"","svg");

now how do I pass this namespace to the context ?
something like xpathRegisterNs that exists in .py (AFAIK)
Python XPath / libxml2 namespace query

If someone got some sample code to get the list of existing namespace in the doc it would be great too.

PS: [*] I say I guessed because I hoped I'd found a good Linux IDE with vala completion. Right now I'm stuck with Monodevelop 2.8.6.3 which has syntax highlighting for vala but no code completion (It keeps saying "fetching information for the class" but I don't get any result). So if someone knows of a good ide, I'll be glad to hear you...


Solution

  • You don't need to create the namespace as an object; that's only needed for registering it with a document. On the Context do:

    ctx.register_ns("svg", "http://www.w3.org/2000/svg");
    ctx.eval_expression("//svg:g");