Search code examples
c#.netasp.net-corexslt

Error during XSLT transformation: An error occurred while loading document 'https://ex.com/example.xml'. See InnerException forcomplete description


I keep getting an error during XSLT transformation: An error occurred while loading document 'https://www.example.com/myxml/example.xml'. See InnerException for a complete description of the error. I pass in a well formed xmldocument and the path to my xslt file. The xslt uses the document function to load the above fake url. Don't worry, the real url is accessible I've tested it. It should be able to do that per the xslt settings allowing that. Additionally, the transformation works in Visual Studio when using the XSL Transform feature. It appears that, no matter the settings, I just can't give the xsl tranformation enough permissions to do it.

static XElement TransformXElement(XElement xmlElement, string xsltFilePath)
{
    try
    {
        // Load the XSLT file
        XslCompiledTransform xslt = new XslCompiledTransform();
        
        XsltSettings settings = new XsltSettings();
        settings.EnableDocumentFunction = true; // Enable document() function if needed

        // Create an XmlUrlResolver with credentials if required
        XmlUrlResolver resolver = new XmlUrlResolver();
        resolver.Credentials = System.Net.CredentialCache.DefaultCredentials; // Example: Use default credentials

        // Load XSLT with resolver and settings
        xslt.Load(xsltFilePath, settings, resolver);

        // Create an XDocument from the XElement
        XDocument xDocument = new XDocument(xmlElement);

        // Prepare an XmlWriter to capture the transformed output
        using (StringWriter stringWriter = new StringWriter())
        using (XmlWriter xmlWriter = XmlWriter.Create(stringWriter, xslt.OutputSettings))
        {
            // Apply the transformation
            xslt.Transform(xDocument.CreateReader(), null, xmlWriter);            

            // Parse the transformed XML string back into an XElement
            return XElement.Parse(stringWriter.ToString());
        }
    }
    catch (Exception ex)
    {
        Console.WriteLine($"Error during XSLT transformation: {ex.Message}");
        return null; // Handle the error appropriately in your application
    }
}

Solution

  • In .NET (Core), I think to have your XmlUrlResolver work as in .NET framework, you first need to set AppContext.SetSwitch("Switch.System.Xml.AllowDefaultResolver", true);, e.g. before XslCompiledTransform xslt = new XslCompiledTransform();.

    Asn an alternative, the direct change to your code would be to make sure you also pass your resolver to the Transform method as the one you pass to the Load method is only for xsl:include/xsl:import while the one passed to Transform is for document calls i.e. xslt.Transform(xDocument.CreateReader(), null, xmlWriter, resolver);.