Namespace Manager or XsltContext needed. This query has a prefix, variable, or user-defined function

C#XmlXml NamespacesXmldocument

C# Problem Overview


I am trying to call SelectNode from XmlDocument class and trouble due to this error:

> Namespace Manager or XsltContext needed. This query has a prefix, variable, or user-defined function.

My code:

   public void Add(ref XmlDocument xmlFormat, String strName)
   {
        XmlDocument dom;
        XSLTemplate xsl = null;
        String strPath = "";
        XmlNodeList nl;
        XmlAttribute na;
        int n;

        nl = (XmlNodeList)xmlFormat.SelectNodes("//xsl:import/@href",nsm);
    }

and xsl:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
	<xsl:import href="stylesheets/r_adresetiket.xsl" />
	<xsl:template match="/">
		<xsl:call-template name="retouradres">
			<xsl:with-param name="_retouradres" select="data/adresetiket/_retouradres" />
			<xsl:with-param name="minofdir" select="data/adresetiket/afzendgegevens/afzendgegevens" />
			<xsl:with-param name="checked" select="data/adresetiket/LB" />
		</xsl:call-template>
	</xsl:template>
</xsl:stylesheet>

C# Solutions


Solution 1 - C#

You have to add xsl namespace to XmlNamespaceManager:

var document = new XmlDocument();
document.Load(...);
var nsmgr = new XmlNamespaceManager(document.NameTable);
nsmgr.AddNamespace("xsl", "http://www.w3.org/1999/XSL/Transform");

var nl = document.SelectNodes("//xsl:import/@href", nsmgr);

Solution 2 - C#

The document can be traversed by GetElementsByTagName and it doesn't necessarily need using XmlNamespaceManager:

var nodes = document.GetElementsByTagName("xsl:import");
var href =  nodes[0].Attributes["href"];

Fiddle

Solution 3 - C#

var document = new XmlDocument();
document.LoadXml(rawData);

var nsmgr = new XmlNamespaceManager(document.NameTable);
nsmgr.AddNamespace("cbc", "urn:xxx"); //for example
nsmgr.AddNamespace("cac", "urn:yyy");            

XmlElement xmlElem = document.DocumentElement;
var node = xmlElem.SelectSingleNode("cac:AccountingSupplierParty/cac:Party/cac:PartyIdentification/cbc:ID[@schemeID='VKN']/text()", nsmgr);
var nodeText = node.InnerText;

enter image description here

All namespaces that will be used in XML should be added.
Then you can access the values of the relevant nodes using xpath.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionrizwan ansariView Question on Stackoverflow
Solution 1 - C#RiaView Answer on Stackoverflow
Solution 2 - C#Daniel BView Answer on Stackoverflow
Solution 3 - C#Furkan ÇELİKCİView Answer on Stackoverflow