Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

An example how to apply xsl transformation to a single XmlNode in C#

Tags:

c#

xml

xslt

Here is what I'm trying to do: I've got an XmlDocument, which is already loaded into memory. I want to apply an xsl transformation to a single node of that document.

here's the code:

var xDoc=GetXmlDocument();
var myNode=xDoc.SelectSingleNode("//node");
var xslTransformer=new XslCompiledTransform(); 
xslTransformer.Load(new XmlTextReader(new StringReader(myXslText)));

Now I need to apply xslTransformer on myNode. Can anyone show me a code example, which does that? What I've seen so far only works with input and output files.

like image 598
Arsen Zahray Avatar asked Dec 29 '25 20:12

Arsen Zahray


1 Answers

Here is an example how to do this, taken from the MSDN documentation:

// Load an XPathDocument.
XPathDocument doc = new XPathDocument("books.xml");

// Locate the node fragment.
XPathNavigator nav = doc.CreateNavigator();
XPathNavigator myBook = nav.SelectSingleNode("descendant::book[@ISBN = '0-201-63361-2']");

// Create a new object with just the node fragment.
XmlReader reader = myBook.ReadSubtree();
reader.MoveToContent();

// Load the style sheet.
XslCompiledTransform xslt = new XslCompiledTransform();
xslt.Load("single.xsl");

// Transform the node fragment.
xslt.Transform(reader, XmlWriter.Create(Console.Out, xslt.OutputSettings));

For more information see: http://technet.microsoft.com/en-us/library/wkx4fcc4.aspx

Do note:

When you transform data contained in an XmlDocument or XPathDocument object the XSLT transformations apply to a document as a whole. In other words, if you pass in a node other than the document root node, this does not prevent the transformation process from accessing all nodes in the loaded document. To transform a node fragment, you must create a separate object containing just the node fragment, and pass that object to the Transform method.

This is why applying the transformation on a node of a document may cause unexpected and unwanted results -- for example the transformation can access other nodes, that aren't in the provided node's subtree -- such as siblings or ancestors.

This is why I strongly recommend not to simply call Transform() on any node (other than a document-node).

like image 132
Dimitre Novatchev Avatar answered Jan 01 '26 10:01

Dimitre Novatchev