CodexBloom - Programming Q&A Platform

XSLT Transformation Not Applying to Namespaced XML Elements in .NET

👀 Views: 52 đŸ’Ŧ Answers: 1 📅 Created: 2025-08-24
xml xslt dotnet C#

I've spent hours debugging this and I'm upgrading from an older version and I'm testing a new approach and I'm relatively new to this, so bear with me... I'm working on transforming an XML document using XSLT in a .NET application, but I'm encountering issues when trying to apply the transformation to elements that are in a namespace. The XML file looks something like this: ```xml <root xmlns:ns="http://example.com/ns"> <ns:item> <ns:name>Item 1</ns:name> </ns:item> </root> ``` My XSLT transformation is as follows: ```xml <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:ns="http://example.com/ns"> <xsl:template match="/"> <result> <xsl:apply-templates select="ns:item" /> </result> </xsl:template> <xsl:template match="ns:item"> <xsl:copy> <xsl:copy-of select="ns:name" /> </xsl:copy> </xsl:template> </xsl:stylesheet> ``` When I run the transformation using `XslCompiledTransform`, I get an empty result: ```csharp var xslt = new XslCompiledTransform(); xslt.Load("transform.xslt"); using (var reader = XmlReader.Create("input.xml")) { using (var writer = XmlWriter.Create("output.xml")) { xslt.Transform(reader, writer); } } ``` However, if I change the XML to remove the namespace, the transformation works perfectly. I'm not sure if I'm missing something with the namespace handling in the XSLT or something specific in .NET. I've checked the XSLT and it seems to be correctly defined with the namespace prefix. I've also tried adding `<xsl:copy-of select="*" />` but I still get no output. Any insights on how to properly handle namespaced elements in XSLT transformations within .NET? Am I overlooking any specific detail regarding namespace handling? I appreciate any insights! Is there a simpler solution I'm overlooking? This is for a web app running on Linux. Any feedback is welcome!