View source with formatted comments or as raw
    1/*  Part of SWI-Prolog
    2
    3    Author:        Jan Wielemaker
    4    E-mail:        J.Wielemaker@vu.nl
    5    WWW:           http://www.swi-prolog.org
    6    Copyright (c)  2009-2023, University of Amsterdam
    7                              VU University Amsterdam
    8                              CWI, Amsterdam
    9                              SWI-Prolog Solutions b.v.
   10    All rights reserved.
   11
   12    Redistribution and use in source and binary forms, with or without
   13    modification, are permitted provided that the following conditions
   14    are met:
   15
   16    1. Redistributions of source code must retain the above copyright
   17       notice, this list of conditions and the following disclaimer.
   18
   19    2. Redistributions in binary form must reproduce the above copyright
   20       notice, this list of conditions and the following disclaimer in
   21       the documentation and/or other materials provided with the
   22       distribution.
   23
   24    THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
   25    "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
   26    LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
   27    FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
   28    COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
   29    INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
   30    BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
   31    LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
   32    CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
   33    LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
   34    ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
   35    POSSIBILITY OF SUCH DAMAGE.
   36*/
   37
   38:- module(xpath,
   39          [ xpath/3,                    % +DOM, +Spec, -Value
   40            xpath_chk/3,                % +DOM, +Spec, -Value
   41
   42            op(400, fx, //),
   43            op(400, fx, /),
   44            op(200, fy, @)
   45          ]).   46:- use_module(library(record),[record/1, op(_,_,record)]).   47
   48:- autoload(library(error),[instantiation_error/1,must_be/2]).   49:- autoload(library(lists),[member/2]).   50:- autoload(library(sgml),[xsd_number_string/2]).   51
   52/** <module> Select nodes in an XML DOM
   53
   54The library xpath.pl provides predicates to select nodes from an XML DOM
   55tree as produced by library(sgml) based  on descriptions inspired by the
   56XPath language.
   57
   58The   predicate   xpath/3   selects   a   sub-structure   of   the   DOM
   59non-deterministically based on an  XPath-like   specification.  Not  all
   60selectors of XPath are implemented, but the ability to mix xpath/3 calls
   61with arbitrary Prolog code  provides  a   powerful  tool  for extracting
   62information from XML parse-trees.
   63
   64@see http://www.w3.org/TR/xpath
   65*/
   66
   67:- record
   68    element(name, attributes, content).   69
   70%!  xpath_chk(+DOM, +Spec, ?Content) is semidet.
   71%
   72%   Semi-deterministic version of xpath/3.
   73
   74xpath_chk(DOM, Spec, Content) :-
   75    xpath(DOM, Spec, Content),
   76    !.
   77
   78%!  xpath(+DOM, +Spec, ?Content) is nondet.
   79%
   80%   Match an element in a DOM structure.   The syntax is inspired by
   81%   XPath, using () rather than  []   to  select  inside an element.
   82%   First we can construct paths using / and //:
   83%
   84%       $ =|//|=Term :
   85%       Select any node in the DOM matching term.
   86%       $ =|/|=Term :
   87%       Match the root against Term.
   88%       $ Term :
   89%       Select the immediate children of the root matching Term.
   90%
   91%   The Terms above are of type   _callable_.  The functor specifies
   92%   the element name. The element name   '*'  refers to any element.
   93%   The name =self= refers to the   top-element  itself and is often
   94%   used for processing matches of an  earlier xpath/3 query. A term
   95%   NS:Term refers to an XML  name   in  the  namespace NS. Optional
   96%   arguments specify additional  constraints   and  functions.  The
   97%   arguments are processed from left  to right. Defined conditional
   98%   argument values are:
   99%
  100%       $ index(?Index) :
  101%       True if the element is the Index-th child of its parent,
  102%       where 1 denotes the first child. Index can be one of:
  103%         $ `Var` :
  104%         `Var` is unified with the index of the matched element.
  105%         $ =last= :
  106%         True for the last element.
  107%         $ =last= - `IntExpr` :
  108%         True for the last-minus-nth element. For example,
  109%         `last-1` is the element directly preceding the last one.
  110%         $ `IntExpr` :
  111%         True for the element whose index equals `IntExpr`.
  112%       $ Integer :
  113%       The N-th element with the given name, with 1 denoting the
  114%       first element. Same as index(Integer).
  115%       $ =last= :
  116%       The last element with the given name. Same as
  117%       index(last).
  118%       $ =last= - IntExpr :
  119%       The IntExpr-th element before the last.
  120%       Same as index(last-IntExpr).
  121%
  122%   Defined function argument values are:
  123%
  124%       $ =self= :
  125%       Evaluate to the entire element
  126%       $ =content= :
  127%       Evaluate to the content of the element (a list)
  128%       $ =text= :
  129%       Evaluates to all text from the sub-tree as an atom
  130%       $ `text(As)` :
  131%       Evaluates to all text from the sub-tree according to
  132%       `As`, which is either `atom` or `string`.
  133%       $ =normalize_space= :
  134%       As =text=, but uses normalize_space/2 to normalise
  135%       white-space in the output
  136%       $ =number= :
  137%       Extract an integer or float from the value.  Ignores
  138%       leading and trailing white-space
  139%       $ =|@|=Attribute :
  140%       Evaluates to the value of the given attribute.  Attribute
  141%       can be a compound term. In this case the functor name
  142%       denotes the attribute and arguments perform transformations
  143%       on the attribute value.  Defined transformations are:
  144%
  145%         - number
  146%         Translate the value into a number using
  147%         xsd_number_string/2 from library(sgml).
  148%         - integer
  149%         As `number`, but subsequently transform the value
  150%         into an integer using the round/1 function.
  151%         - float
  152%         As `number`, but subsequently transform the value
  153%         into a float using the float/1 function.
  154%         - atom
  155%         Translate the value into a Prolog atom.  Note that
  156%         an atom is normally the default, so ``@href`` and
  157%         ``@href(atom)`` are equivalent.  The SGML parser
  158%         can return attributes as strings using the
  159%         attribute_value(string) option.
  160%         - string
  161%         Translate the value into a Prolog string.
  162%         - lower
  163%         Translate the value to lower case, preserving
  164%         the type.
  165%         - upper
  166%         Translate the value to upper case, preserving
  167%         the type.
  168%
  169%   In addition, the argument-list can be _conditions_:
  170%
  171%       $ Left = Right :
  172%       Succeeds if the left-hand unifies with the right-hand.
  173%       If the left-hand side is a function, this is evaluated.
  174%       The right-hand side is _never_ evaluated, and thus the
  175%       condition `content = content` defines that the content
  176%       of the element is the atom `content`.
  177%       The functions `lower_case` and `upper_case` can be applied
  178%       to Right (see example below).
  179%       $ contains(Haystack, Needle) :
  180%       Succeeds if Needle is a sub-string of Haystack.
  181%       $ XPath :
  182%       Succeeds if XPath matches in the currently selected
  183%       sub-DOM.  For example, the following expression finds
  184%       an =h3= element inside a =div= element, where the =div=
  185%       element itself contains an =h2= child with a =strong=
  186%       child.
  187%
  188%         ==
  189%         //div(h2/strong)/h3
  190%         ==
  191%
  192%       This is equivalent to the conjunction of XPath goals below.
  193%
  194%         ==
  195%            ...,
  196%            xpath(DOM, //(div), Div),
  197%            xpath(Div, h2/strong, _),
  198%            xpath(Div, h3, Result)
  199%         ==
  200%
  201%   **Examples**:
  202%
  203%   Match each table-row in DOM:
  204%
  205%       ==
  206%       xpath(DOM, //tr, TR)
  207%       ==
  208%
  209%   Match the last cell  of  each   tablerow  in  DOM.  This example
  210%   illustrates that a result can be the input of subsequent xpath/3
  211%   queries. Using multiple queries  on   the  intermediate  TR term
  212%   guarantee that all results come from the same table-row:
  213%
  214%       ==
  215%       xpath(DOM, //tr, TR),
  216%       xpath(TR,  /td(last), TD)
  217%       ==
  218%
  219%   Match each =href= attribute in an <a> element
  220%
  221%       ==
  222%       xpath(DOM, //a(@href), HREF)
  223%       ==
  224%
  225%   Suppose we have a table containing  rows where each first column
  226%   is the name of a product with a   link to details and the second
  227%   is the price (a number).  The   following  predicate matches the
  228%   name, URL and price:
  229%
  230%       ==
  231%       product(DOM, Name, URL, Price) :-
  232%           xpath(DOM, //tr, TR),
  233%           xpath(TR, td(1), C1),
  234%           xpath(C1, /self(normalize_space), Name),
  235%           xpath(C1, a(@href), URL),
  236%           xpath(TR, td(2, number), Price).
  237%       ==
  238%
  239%   Suppose we want to select  books   with  genre="thriller" from a
  240%   tree containing elements =|<book genre=...>|=
  241%
  242%       ==
  243%       thriller(DOM, Book) :-
  244%           xpath(DOM, //book(@genre=thiller), Book).
  245%       ==
  246%
  247%   Match the elements =|<table align="center">|= _and_ =|<table
  248%   align="CENTER">|=:
  249%
  250%       ```prolog
  251%           //table(@align(lower) = center)
  252%       ```
  253%
  254%   Get the `width` and `height` of a `div` element as a number,
  255%   and the `div` node itself:
  256%
  257%       ==
  258%           xpath(DOM, //div(@width(number)=W, @height(number)=H), Div)
  259%       ==
  260%
  261%   Note that `div` is an infix operator, so parentheses must be
  262%   used in cases like the following:
  263%
  264%       ==
  265%           xpath(DOM, //(div), Div)
  266%       ==
  267
  268xpath(DOM, Spec, Content) :-
  269    in_dom(Spec, DOM, Content).
  270
  271in_dom(//Spec, DOM, Value) :-
  272    !,
  273    element_spec(Spec, Name, Modifiers),
  274    sub_dom(I, Len, Name, E, DOM),
  275    modifiers(Modifiers, I, Len, E, Value).
  276in_dom(/Spec, E, Value) :-
  277    !,
  278    element_spec(Spec, Name, Modifiers),
  279    (   Name == self
  280    ->  true
  281    ;   element_name(E, Name)
  282    ),
  283    modifiers(Modifiers, 1, 1, E, Value).
  284in_dom(A/B, DOM, Value) :-
  285    !,
  286    in_dom(A, DOM, Value0),
  287    in_dom(B, Value0, Value).
  288in_dom(A//B, DOM, Value) :-
  289    !,
  290    in_dom(A, DOM, Value0),
  291    in_dom(//B, Value0, Value).
  292in_dom(Spec, element(_, _, Content), Value) :-
  293    element_spec(Spec, Name, Modifiers),
  294    count_named_elements(Content, Name, CLen),
  295    CLen > 0,
  296    nth_element(N, Name, E, Content),
  297    modifiers(Modifiers, N, CLen, E, Value).
  298
  299element_spec(Var, _, _) :-
  300    var(Var),
  301    !,
  302    instantiation_error(Var).
  303element_spec(NS:Term, NS:Name, Modifiers) :-
  304    !,
  305    callable_name_arguments(Term, Name0, Modifiers),
  306    star(Name0, Name).
  307element_spec(Term, Name, Modifiers) :-
  308    !,
  309    callable_name_arguments(Term, Name0, Modifiers),
  310    star(Name0, Name).
  311
  312callable_name_arguments(Atom, Name, Arguments) :-
  313    atom(Atom),
  314    !,
  315    Name = Atom, Arguments = [].
  316callable_name_arguments(Compound, Name, Arguments) :-
  317    compound_name_arguments(Compound, Name, Arguments).
  318
  319
  320star(*, _) :- !.
  321star(Name, Name).
  322
  323
  324%!  sub_dom(-Index, -Count, +Name, -Sub, +DOM) is nondet.
  325%
  326%   Sub is a node in DOM with Name.
  327%
  328%   @param Count    is the total number of nodes in the content
  329%                   list Sub appears that have the same name.
  330%   @param Index    is the 1-based index of Sub of nodes with
  331%                   Name.
  332
  333sub_dom(1, 1, Name, DOM, DOM) :-
  334    element_name(DOM, Name0),
  335    \+ Name \= Name0.
  336sub_dom(N, Len, Name, E, element(_,_,Content)) :-
  337    !,
  338    sub_dom_2(N, Len, Name, E, Content).
  339sub_dom(N, Len, Name, E, Content) :-
  340    is_list(Content),
  341    sub_dom_2(N, Len, Name, E, Content).
  342
  343sub_dom_2(N, Len, Name, Element, Content) :-
  344    (   count_named_elements(Content, Name, Len),
  345        nth_element(N, Name, Element, Content)
  346    ;   member(element(_,_,C2), Content),
  347        sub_dom_2(N, Len, Name, Element, C2)
  348    ).
  349
  350
  351%!  count_named_elements(+Content, +Name, -Count) is det.
  352%
  353%   Count is the number of nodes with Name in Content.
  354
  355count_named_elements(Content, Name, Count) :-
  356    count_named_elements(Content, Name, 0, Count).
  357
  358count_named_elements([], _, Count, Count).
  359count_named_elements([element(Name,_,_)|T], Name0, C0, C) :-
  360    \+ Name \= Name0,
  361    !,
  362    C1 is C0+1,
  363    count_named_elements(T, Name0, C1, C).
  364count_named_elements([_|T], Name, C0, C) :-
  365    count_named_elements(T, Name, C0, C).
  366
  367
  368%!  nth_element(?N, +Name, -Element, +Content:list) is nondet.
  369%
  370%   True if Element is the N-th element with name in Content.
  371
  372nth_element(N, Name, Element, Content) :-
  373    nth_element_(1, N, Name, Element, Content).
  374
  375nth_element_(I, N, Name, E, [H|T]) :-
  376    element_name(H, Name0),
  377    \+ Name \= Name0,
  378    !,
  379    (   N = I,
  380        E = H
  381    ;   I2 is I + 1,
  382        (   nonvar(N), I2 > N
  383        ->  !, fail
  384        ;   true
  385        ),
  386        nth_element_(I2, N, Name, E, T)
  387    ).
  388nth_element_(I, N, Name, E, [_|T]) :-
  389    nth_element_(I, N, Name, E, T).
  390
  391
  392%!  modifiers(+Modifiers, +I, +Clen, +DOM, -Value)
  393%
  394%
  395
  396modifiers([], _, _, Value, Value).
  397modifiers([H|T], I, L, Value0, Value) :-
  398    modifier(H, I, L, Value0, Value1),
  399    modifiers(T, I, L, Value1, Value).
  400
  401modifier(M, _, _, _, _) :-
  402    var(M),
  403    !,
  404    instantiation_error(M).
  405modifier(Index, I, L, Value0, Value) :-
  406    implicit_index_modifier(Index),
  407    !,
  408    Value = Value0,
  409    index_modifier(Index, I, L).
  410modifier(index(Index), I, L, Value, Value) :-
  411    !,
  412    index_modifier(Index, I, L).
  413modifier(Function, _, _, In, Out) :-
  414    xpath_function(Function),
  415    !,
  416    xpath_function(Function, In, Out).
  417modifier(Function, _, _, In, Out) :-
  418    xpath_condition(Function, In),
  419    Out = In.
  420
  421implicit_index_modifier(I) :-
  422    integer(I),
  423    !.
  424implicit_index_modifier(last).
  425implicit_index_modifier(last-_Expr).
  426
  427index_modifier(Var, I, _L) :-
  428    var(Var),
  429    !,
  430    Var = I.
  431index_modifier(last, I, L) :-
  432    !,
  433    I =:= L.
  434index_modifier(last-Expr, I, L) :-
  435    !,
  436    I =:= L-Expr.
  437index_modifier(N, I, _) :-
  438    N =:= I.
  439
  440xpath_function(self, DOM, Value) :-                            % self
  441    !,
  442    Value = DOM.
  443xpath_function(content, Element, Value) :-                     % content
  444    !,
  445    element_content(Element, Value).
  446xpath_function(text, DOM, Text) :-                             % text
  447    !,
  448    text_of_dom(DOM, atom, Text).
  449xpath_function(text(As), DOM, Text) :-                         % text(As)
  450    !,
  451    text_of_dom(DOM, As, Text).
  452xpath_function(normalize_space, DOM, Text) :-                  % normalize_space
  453    !,
  454    text_of_dom(DOM, string, Text0),
  455    normalize_space(atom(Text), Text0).
  456xpath_function(number, DOM, Number) :-                         % number
  457    !,
  458    text_of_dom(DOM, string, Text0),
  459    normalize_space(string(Text), Text0),
  460    catch(xsd_number_string(Number, Text), _, fail).
  461xpath_function(@Name, element(_, Attrs, _), Value) :-          % @Name
  462    !,
  463    (   atom(Name)
  464    ->  memberchk(Name=Value, Attrs)
  465    ;   compound(Name)
  466    ->  compound_name_arguments(Name, AName, AOps),
  467        memberchk(AName=Value0, Attrs),
  468        translate_attribute(AOps, Value0, Value)
  469    ;   member(Name=Value, Attrs)
  470    ).
  471xpath_function(quote(Value), _, Value).                         % quote(Value)
  472
  473xpath_function(self).
  474xpath_function(content).
  475xpath_function(text).
  476xpath_function(text(_)).
  477xpath_function(normalize_space).
  478xpath_function(number).
  479xpath_function(@_).
  480xpath_function(quote(_)).
  481
  482translate_attribute([], Value, Value).
  483translate_attribute([H|T], Value0, Value) :-
  484    translate_attr(H, Value0, Value1),
  485    translate_attribute(T, Value1, Value).
  486
  487translate_attr(number, Value0, Value) :-
  488    xsd_number_string(Value, Value0).
  489translate_attr(integer, Value0, Value) :-
  490    xsd_number_string(Value1, Value0),
  491    Value is round(Value1).
  492translate_attr(float, Value0, Value) :-
  493    xsd_number_string(Value1, Value0),
  494    Value is float(Value1).
  495translate_attr(atom, Value0, Value) :-
  496    atom_string(Value, Value0).
  497translate_attr(string, Value0, Value) :-
  498    atom_string(Value0, Value).
  499translate_attr(lower, Value0, Value) :-
  500    (   atom(Value0)
  501    ->  downcase_atom(Value0, Value)
  502    ;   string_lower(Value0, Value)
  503    ).
  504translate_attr(upper, Value0, Value) :-
  505    (   atom(Value0)
  506    ->  upcase_atom(Value0, Value)
  507    ;   string_upper(Value0, Value)
  508    ).
  509
  510xpath_condition(Left = Right, Value) :-                        % =
  511    !,
  512    var_or_function(Left, Value, LeftValue),
  513    process_equality(LeftValue, Right).
  514xpath_condition(contains(Haystack, Needle), Value) :-          % contains(Haystack, Needle)
  515    !,
  516    val_or_function(Haystack, Value, HaystackValue),
  517    val_or_function(Needle, Value, NeedleValue),
  518    atom(HaystackValue), atom(NeedleValue),
  519    (   sub_atom(HaystackValue, _, _, _, NeedleValue)
  520    ->  true
  521    ).
  522xpath_condition(Spec, Dom) :-
  523    in_dom(Spec, Dom, _).
  524
  525
  526%!  process_equality(+Left, +Right) is semidet.
  527%
  528%   Provides (very) partial support for XSLT   functions that can be
  529%   applied according to the XPath 2 specification.
  530%
  531%   For example the XPath expression  in   [1],  and  the equivalent
  532%   Prolog expression in [2], would both   match the HTML element in
  533%   [3].
  534%
  535%     ==
  536%     [1] //table[align=lower-case(center)]
  537%     [2] //table(@align=lower_case(center))
  538%     [3] <table align="CENTER">
  539%     ==
  540
  541process_equality(Left, Right) :-
  542    var(Right),
  543    !,
  544    Left = Right.
  545process_equality(Left, lower_case(Right)) :-
  546    !,
  547    downcase_atom(Left, Right).
  548process_equality(Left, upper_case(Right)) :-
  549    !,
  550    upcase_atom(Left, Right).
  551process_equality(Left, Right) :-
  552    Left = Right,
  553    !.
  554process_equality(Left, Right) :-
  555    atom(Left),
  556    atomic(Right),
  557    \+ atom(Left),
  558    atom_string(Left, Right).
  559
  560var_or_function(Arg, _, Arg) :-
  561    var(Arg),
  562    !.
  563var_or_function(Func, Value0, Value) :-
  564    xpath_function(Func),
  565    !,
  566    xpath_function(Func, Value0, Value).
  567var_or_function(Value, _, Value).
  568
  569val_or_function(Arg, _, Arg) :-
  570    var(Arg),
  571    !,
  572    instantiation_error(Arg).
  573val_or_function(Func, Value0, Value) :-                         % TBD
  574    xpath_function(Func, Value0, Value),
  575    !.
  576val_or_function(Value, _, Value).
  577
  578
  579%!  text_of_dom(+DOM, +As, -Text:atom) is det.
  580%
  581%   Text is the joined textual content of DOM.
  582
  583text_of_dom(DOM, As, Text) :-
  584    phrase(text_of(DOM), Tokens),
  585    (   As == atom
  586    ->  atomic_list_concat(Tokens, Text)
  587    ;   As == string
  588    ->  atomics_to_string(Tokens, Text)
  589    ;   must_be(oneof([atom,string]), As)
  590    ).
  591
  592text_of(element(_,_,Content)) -->
  593    text_of_list(Content).
  594text_of([]) -->
  595    [].
  596text_of([H|T]) -->
  597    text_of(H),
  598    text_of(T).
  599
  600
  601text_of_list([]) -->
  602    [].
  603text_of_list([H|T]) -->
  604    text_of_1(H),
  605    text_of_list(T).
  606
  607
  608text_of_1(element(_,_,Content)) -->
  609    !,
  610    text_of_list(Content).
  611text_of_1(Data) -->
  612    { atom_or_string(Data) },
  613    !,
  614    [Data].
  615text_of_1(_) -->                % pi(_), sdata(_), ndata(_), ...
  616    [].
  617
  618atom_or_string(Data) :-
  619    (   atom(Data)
  620    ->  true
  621    ;   string(Data)
  622    )