Une fonction qui peut s'avérer pratique lorsqu'on souhaite charger un document XML, lui appliquer un XSL pour générer un nouveau XML.

 

/// <summary>
/// Allows to apply a XSL transformation
/// </summary>
/// <param name="xmlDoc">XML document path</param>
/// <param name="xslDoc">XSL document path</param>
/// <returns></returns>
private XmlDocument ApplyXSLTransformation(String xmlDocPath, String xslDocPath)

     XmlDocument outputXmlDoc = new XmlDocument();

     try 
     {

   // Loads the XML document
  
XmlDocument xmlDoc = new XmlDocument();
   xmlDoc.Load(xmlDoc);
   XmlNodeReader reader = new XmlNodeReader(xmlDoc);

     // Settings to apply for the transformation     
 
  XsltSettings settings = new XsltSettings();  
   settings.EnableDocumentFunction = true;

   // Object to apply XSL
   XslCompiledTransform xslt = new XslCompiledTransform(true);
  
xslt.Load(xslDocPath, settings, null);

  // Used to get generated XML/HTML according to the wished output format
  
StringBuilder transformOutput = new StringBuilder();

    // XML writer + settings to write the stream results    
   XmlWriterSettings
writerSettings = new XmlWriterSettings();
  
writerSettings.ConformanceLevel = ConformanceLevel.Auto;

      XmlWriter htmlDoc = System.Xml.XmlWriter.Create(transformOutput, xslt.OutputSettings);

  // Applies transformation
 
xslt.Transform(reader, null, htmlDoc, new XmlUrlResolver());

  // Loads the resulting stream in the XML document   

outputXmlDoc.InnerXml = transformOutput.ToString();

   } 
   catch (XmlException ex) {   // To define             }
  
catch (ArgumentNullException ex) {//To define        } 
 
  catch (XsltException ex) {  // To define }

   return outputXmlDoc;

}

 

Pour plus d'information sur XslCompiledTransform et XmlWriterSettings :

 

Publié le 19/05/2008  par Michel Hubert