Manoj Singh
Manoj Singh

Reputation: 7707

How to transform XMLDocument using XSLT in C# 2.0

I am using C# 2.0 and I have got below code:

  XmlDocument doc = new XmlDocument();
  doc.LoadXml(GetListOfPagesInStructureGroup(m_Page.Id));

In above I am loading my XMLDocument with method which returns as string, now after some processing on above xmldocument I want to apply XSLT on the above XMLDocument to render my desired result according to XSLT and finally my function will return whole rendered XML as string

Please suggest!!

Upvotes: 3

Views: 12508

Answers (4)

Michael G. Workman
Michael G. Workman

Reputation: 375

There are lots of examples on the web of transforming an XML file to a different format using an XSLT file, like the following:

XslTransform myXslTransform = new XslTransform();
XsltSettings myXsltSettings = new XsltSettings();
myXsltSettings.EnableDocumentFunction = true;
myXslTransform.Load("transform.xsl");
myXslTransform.Transform("input.xml", "output.xml");

However this is only a partial answer, I would like to be able to get the XML input data from a web form and use that as the input data instead of an '.xml' file, but have not found any concrete examples, also using Visual Studio I can see the different constructors and methods that are available and I am not seeing one that accepts xml data in a string format, so it would be very helpful if someone could provide an example of that.

Upvotes: 1

Manoj Singh
Manoj Singh

Reputation: 7707

Please suggest on below solution:

        XslCompiledTransform xslTransform = new XslCompiledTransform();
        StringWriter writer = new StringWriter();          
        xslTransform.Load("xslt/RenderDestinationTabXML.xslt");
        xslTransform.Transform(doc.CreateNavigator(),null, writer);
        return writer.ToString();

Thanks!!

Upvotes: 8

Marc Gravell
Marc Gravell

Reputation: 1062494

Re " I want my same XMlDocument updated " - it doesn't work like that; the output is separate to the input. If that is important, just use a StringWriter or MemoryStream as the destination, then reload the XmlDocument from the generated output.

Consider in particular: the output from an xslt transformation does not have to be xml, and also: the xslt is most likely using the node tree during the operation; changing the structure in-place would make that very hard.

Upvotes: 0

Petar Ivanov
Petar Ivanov

Reputation: 93000

Try the XslCompiledTransform class.

Upvotes: 2

Related Questions