Pages

Showing posts with label xpath. Show all posts
Showing posts with label xpath. Show all posts

Friday, January 06, 2012

XSL transformation on XML document Using C#

Here is a pretty simple way for transforming an XML document using XSL through C#.

First you get your XML file, by string or file location using Load method, then using XmlTextWriter and XmlTextReader you apply the XSL and get the result on a StringBuilder... It seems cool right?

Now, what have bring you here... the code...


XmlDocument doc = new XmlDocument();
doc.LoadXml("Xml as a String");

StringBuilder resultString = new StringBuilder();
using (XmlTextWriter xmlWriter = new XmlTextWriter(new StringWriter(resultString)))
{
    using (XmlTextReader xmlReader = new XmlTextReader(new StringReader(doc.OuterXml)))
    {
        string xslUrl = "http://YourHost/xsl/stylesheet.xsl";
        System.Xml.Xsl.XslCompiledTransform xslTransform = new System.Xml.Xsl.XslCompiledTransform();
        xslTransform.Load(xslUrl);
        xslTransform.Transform(xmlReader, xmlWriter);
    }
}
                
XmlDocument doc2 = new XmlDocument();
doc2.LoadXml(resultString.ToString());



Cheers!

References:
http://stackoverflow.com/questions/982600/net-xslt-transformation-is-this-really-streamed
http://msmvps.com/blogs/coad/archive/2004/04/13/4994.aspx
http://www.csharpfriends.com/Articles/getArticle.aspx?articleID=63
http://support.microsoft.com/kb/307322/en-us
http://www.codeproject.com/KB/cs/xsltrafo.aspx

Tuesday, August 23, 2011

Remove xmlns from XML doc (C#) for use of X-Path

That's right!!!

I was using X-Path to read the nodes from an XML doc, but when I try doing it, it was always wrong.

Why? Because Microsoft Core XML, even the most recent one (you can see it here), only implements the X-Path 1.0 (since 1999).












And this X-Path version does not support the default namespace.

To overpass this problem, you can do 3 things:

  • Add the namespace to the XmlDocument and then use X-Path
  • Remove the namespace from the XmlDocument and then use X-Path
  • Use third dll's that implement newer versions of X-Path

There's some of solutions all over internet, but I prefer an generic solution, like removing all namespaces.

You can do it directly on XmlDocument or use regular expressions.

Personally, I like the regular expressions solution. Here it is:



This way you have an generic solution for all xml document and you can use X-Path with no worries.


Special Thanks to Pedro Lamas giving references and orientation.


References:
http://www.java2s.com/Code/CSharp/XML/Removeallthexmlnamespacesxmlnsattributesinthexmlstring.htm
http://stackoverflow.com/questions/987135/how-to-remove-all-namespaces-from-xml-with-c
http://www.eggheadcafe.com/community/aspnet/2/10021509/problem-with-xpath.aspx
http://www.microsoft.com/download/en/details.aspx?displaylang=en&id=3988