2

Does anyone know if I can find out if my xml file contains a certain namespace (where no elements are given that name).

Somthing among the lines of

<xsl:if test="count(xmlns:name)!=0" >

</xsl:if>

this does not work, as I get the error "the prefix xmlns" is not defined.

2
  • When you say "where no elements are given that name", do you mean you are only looking for namespaces that are not used in any element name, or do you mean that you are looking for the namespace whether or not it is used in an element name? Commented Mar 20, 2020 at 22:23
  • Hi, I sorry I missed your comment earlier. I mean whether or not it is used in an element name. @michael.hor.257k had a good solution :) Commented Mar 23, 2020 at 13:45

2 Answers 2

1

find out if my xml file contains a certain namespace (where no elements are given that name).

It is difficult to understand what exactly you mean by that. If you want to find out if the input XML contains a namespace declaration using a given namespace URI, regardless of whether this declaration is used to place any of the XML's nodes in said namespace or not, you can use a test in the form of:

<xsl:if test="//namespace::*[.='your-namespace-URI']">

Example:

XML

<root xmlns:ns1="http://example.com/a">
    <item>Alpha</item>
    <item>Bravo</item>
    <item>Charlie</item>
</root>

XSLT 1.0

<xsl:stylesheet version="1.0" 
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>

<xsl:template match="/">
    <result>
        <xsl:if test="//namespace::*[.='http://example.com/a']">YES</xsl:if>
    </result>
</xsl:template>

</xsl:stylesheet>

Result

<?xml version="1.0" encoding="UTF-8"?>
<result>YES</result>

The result here is positive, even though the XML has no nodes that are actually in the "http://example.com/a" namespace.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks! This was exactly what I was looking for!
0

You can check e.g. //pf:* while declaring xmlns:pf="http://example.com/ns" in your XSLT code to check if there are any elements in the namespace http://example.com/ns. Or you can check //*[namespace-uri() = 'http://example.com/ns'] without declaring the namespace in the XSLT. Both checks assume that namespace means a certain namespace URI and not a certain prefix.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.