Saravanan
Saravanan

Reputation: 11592

How to pass and get the string based xml data in xslt transform using C#?

I want to convert one xml file into another xml file using xslt.here, i can able to pass the input document to the XPathDocument and also save the output file in disk by passing outfile into XmlTextWriter.

But now my problem is... i have my input is in string format and i also want output as a string.Instead of passing the location of the input file, i want to pass string that contains the xml data.

so i have to pass string object into xpathDoccument in someway and also get the resultant xml file as a string.Instead of save the output as a file,i want output as a string.

            XPathDocument xpathDoc = new XPathDocument("C:\\InputXml.xml");
            XslCompiledTransform xslt = new XslCompiledTransform();

            string xsltFile = "C:\\conversion.xslt";
            xslt.Load(xsltFile);

            string outputFile = "C:\\myHtml.html";
            XmlTextWriter writer = new XmlTextWriter(outputFile, null);
            xslt.Transform(xpathDoc, null, writer);
            writer.Close();

Please guide me to get out of this issue...

Upvotes: 0

Views: 817

Answers (2)

L.B
L.B

Reputation: 116108

XPathDocument accepts TextReader. You can give a stream as new XPathDocument(new StringReader(xmlstring)). Similarly XmlTextWriter accepts TextWriter. So you can pass a StringWriter.

--edit--

var sw = new StringWriter();
XmlTextWriter writer = new XmlTextWriter(sw);
xslt.Transform(xpathDoc, null, writer);
var str= sw.ToString();

Upvotes: 2

Rajesh Subramanian
Rajesh Subramanian

Reputation: 6490

Try this,

XslTransform  xTrans = new XslTransform();
xTrans.Load(nodeXsltPath);    //xsl file path
XmlDocument input= new XmlDocument();
XmlDocument output= new XmlDocument();
input.LoadXml(xmlString); /* Xml string to be loaaded */                        
output.Load(xTrans.Transform(input,null,new XmlUrlResolver()));
output.Save(filePathtoSave);

Upvotes: 1

Related Questions