| 1 | //////////////////////////////////////////////////////////////////////////////////////////////////////////////////// |
| 2 | // Copyright (c) 2018 Saxonica Limited. |
| 3 | // This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. |
| 4 | // If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/. |
| 5 | // This Source Code Form is "Incompatible With Secondary Licenses", as defined by the Mozilla Public License, v. 2.0. |
| 6 | //////////////////////////////////////////////////////////////////////////////////////////////////////////////////// |
| 7 | |
| 8 | package net.sf.saxon.functions; |
| 9 | |
| 10 | import net.sf.saxon.expr.Callable; |
| 11 | import net.sf.saxon.expr.XPathContext; |
| 12 | import net.sf.saxon.om.*; |
| 13 | import net.sf.saxon.trans.XPathException; |
| 14 | import net.sf.saxon.value.AnyURIValue; |
| 15 | import net.sf.saxon.value.StringValue; |
| 16 | |
| 17 | |
| 18 | /** |
| 19 | * This class supports the function namespace-uri-for-prefix() |
| 20 | */ |
| 21 | |
| 22 | public class NamespaceForPrefix extends SystemFunction implements Callable { |
| 23 | |
| 24 | /** |
| 25 | * Evaluate the expression |
| 26 | * |
| 27 | * @param context the dynamic evaluation context |
| 28 | * @param arguments the values of the arguments, supplied as Sequences |
| 29 | * @return the result of the evaluation, in the form of a Sequence |
| 30 | * @throws net.sf.saxon.trans.XPathException |
| 31 | * if a dynamic error occurs during the evaluation of the expression |
| 32 | */ |
| 33 | public ZeroOrOne<AnyURIValue> call(XPathContext context, Sequence[] arguments) throws XPathException { |
| 34 | AnyURIValue result = namespaceUriForPrefix((StringValue) arguments[0].head(), (NodeInfo) arguments[1].head()); |
| 35 | return new ZeroOrOne<>(result); |
| 36 | } |
| 37 | |
| 38 | /** |
| 39 | * Private supporting method |
| 40 | * |
| 41 | * @param p the prefix |
| 42 | * @param element the element node |
| 43 | * @return the corresponding namespace, or null if not in scope |
| 44 | */ |
| 45 | |
| 46 | /*@Nullable*/ |
| 47 | private static AnyURIValue namespaceUriForPrefix(StringValue p, NodeInfo element) { |
| 48 | String prefix; |
| 49 | if (p == null) { |
| 50 | prefix = ""; |
| 51 | } else { |
| 52 | prefix = p.getStringValue(); |
| 53 | } |
| 54 | NamespaceResolver resolver = new InscopeNamespaceResolver(element); |
| 55 | String uri = resolver.getURIForPrefix(prefix, true); |
| 56 | if (uri == null || uri.isEmpty()) { |
| 57 | return null; |
| 58 | } |
| 59 | return new AnyURIValue(uri); |
| 60 | } |
| 61 | |
| 62 | } |
| 63 |