I'd like to transform a string that contains an xml using a XSLT, it's for a Colombian company, so I have the following code (don't try to understand it):
string xmlTFDNode = #<tfd:TimbreFiscalDigital xmlns:tfd="http://www.sat.gob.mx/TimbreFiscalDigital" xsi:schemaLocation="http://www.sat.gob.mx/TimbreFiscalDigital TimbreFiscalDigital.xsd" selloCFD="tOSe+Ex/wvn33YlGwtfmrJwQ31Crd7lI9VcH63TGjHfxk5vfb3q9uSbDUGk9TXvo70ydOpikRVw+9B2Six0m bu3PjoPpO909oAYITrRyomdeUGJ4vmA2/12L86EJLWpU7vIt4cL8HpkEw7TOFhSdpzb/890+jP+C1adBsHU1VHc=" FechaTimbrado="2010-03-06T20:40:10" UUID="ad662d33-6934-459c-a128-bdf0393e0f44" noCertificadoSAT="30001000000100000801" version="1.0" selloSAT="j5bSpqM3w0+shGtImqOwqqy6+d659O78ckfstu5vTSFa+2CVMj6Awfr18x4yMLGBwk6ruYbjBlVURodEIl6n JIhTTUtYQV1cbRDG9kvvhaNAakxqaSOnOx79nHxqFPRVoqh10CsjocS9PZkSM2jz1uwLgaF0knf1g8pjDkLYwlk="/>
and I have a XLST stored on the server named InvoiceTFD.xslt
This is the XSLT file
I want to create a method to return a string with the data transformed, it shoud look like this (that's what the XSLT does):
||1.0|ad662d33-6934-459c-a128-bdf0393e0f44|2001-12-
17T09:30:47Z|iYyIk1MtEPzTxY3h57kYJnEXNae9lvLMgAq3jGMePsDtEOF6XLWbrV2GL/
2TX00vP2+YsPN+5UmyRdzMLZGEfESiNQF9fotNbtA487dWnCf5pUu0ikVpgHvpY7YoA4
lB1D/JWc+zntkgW+Ig49WnlKyXi0LOlBOVuxckDb7EAx4=|12345678901234 567890||
The problem I is that the XslTransform.Transform method creates a new file, and I don't want to write a file
Recapitulating, I just want to take a string, transform it using a XSLT file I have, and return a string with the transformation without creating files on the server, that's it!
I believe it's not that hard, but I'm new in .NET so I really don't know how to do it :(
Thanks in advance and have a great day guys !!
You can write to a memory stream:
MemoryStream oStream = new MemoryStream()
oXslt.Transform(new XPathDocument(new XmlNodeReader(oXml)), null, oStream );
oStream.Position = 0
StreamReader oReader = new StreamReader(oStream);
string output = oReader.ReadToEnd();
BTW, use XPathDocument and XslCompiledTransform. They are much faster than XslTransform and XmlDocument. Even if you use an XmlDocument to create the xml, covert it to an XPathDocument for the transform.
Transform method can take Stream outputStream parameter. You can create StringWriter and pass it as output stream.
Use XslCompiledTransform instead of XslTransform. Use method: XslCompiledTransform.Transform, save result to OutputStream.
As I see, your XSLT is version 2.0. Neither of them support XSLT 2.0.
Related
i am exporting excel by transform xml,xslt into xls.
Below is my coding :
ds.WriteXml(MyXmlPath);
XPathDocument xmlDoc = new XPathDocument(MyXmlPath);
XslCompiledTransform XSLTransform = new XslCompiledTransform();
XSLTransform.Load(AppBasePath + #"\Master\XSLT\" + strSelectedXSLT.ToString() + ".xslt");
XSLTransform.Transform(MyXmlPath, MyExcelPath);
From the above coding i am write xml into disk for the given path by using dataset. And read from the disk path in order to transform xls file.
****PROBLEM : Instead of writing & Reading the xml content , why should i write the xml content into string and convert **BECAUSE ITS TAKE HEAVY TIME TO WRITE EXCEL. so i tried below coding . But its not working . ******
StringWriter sw = new StringWriter();
ds.WriteXml(sw, XmlWriteMode.IgnoreSchema);
string xmlcontent = sw.ToString();
XslCompiledTransform XSLTransform = new XslCompiledTransform();
XSLTransform.Load(AppBasePath + #"\Master\XSLT\" + strSelectedXSLT.ToString() + ".xslt");
XSLTransform.Transform(xmlcontent, MyExcelPath);
Any suggestions ?
When using Transform(string,string) both of the parameters should be URI. In your first code example you're using a file URI for the BOTH parameters of Transform(). This is correct. For the second example, you have tried to pass in the xml content not a URI as a string for the first parameter. I dont know why you didn't see an exception at this point.
If you want to pass xml content directly into Transform() you will need to use one of other method signatures that accepts an XmlReader or IXPathNavigable for the xml input. However, when using one of these other Transform() signatures, you'll also need to Stream the output to a file or use XmlWriter
Check out this: How to transform XML as a string w/o using files in .NET?
I am using http://www.thescarms.com/dotnet/XSLT.aspx to Convert comma delimited data (CSV) to XML using XSLT template.
It uses the foll. 2 lines of .NET code:
XSLT.Load(mstrInputXSLTFile, resolver);
XSLT.Transform(mstrInputCSVFile, mstrOutputXMLFile, resolver);
I am looking for a way in which I can use the string contents (contents of the XSLT, CSV file) instead of files in above 2 methods.. Any help will be usefull.
I am planning to implement this logic in a WCF webservice which will receive the csv string. If there is no workaround then I will have to create temp files based on the values of csv and xsl received. Process the conversion of csv to xml on the server and return the xml output to the client. Then delete the files created above.
If you want to load the input from a string then create an XmlReader over a StringReader over your string e.g.
XslCompiledTransform proc = new XslCompiledTransform();
using (StringReader sr = new StringReader(stringVar))
{
using (XmlReader xr = XmlReader.Create(sr))
{
proc.Load(xr);
}
}
There is no suitable method in XslTransform which does what you want.
However, you could write your own extensions methods (I would call them Parse..), which take content as string, create files in the temporary directory, and load/transform them by the suitable methods.
In .NET C#, when trying to load a string into xml, you need to use XmlDocument type from System.Xml and do the following:
e.g:
string xmlStr = "<name>Oscar</name>";
XmlDocument doc = new XmlDocument();
doc.LoadXml(xmlStr);
Console.Write(doc.OuterXml);
This seems simple but how can I do this in Java? Is it possible to load a string into xml using something directly, short and simple like above and avoid implementing other methods for this?
Thanks in advance.
Try this:
DocumentBuilderFactory documentBuildFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder doccumentBuilder = documentBuildFactory.newDocumentBuilder();
Document document =
doccumentBuilder.parse(new ByteArrayInputStream("<name>Oscar</name>".getBytes()));
You can traverse Oscar by:
String nodeText = document.getChildNodes().item(0).getTextContent() ;
System.out.println(nodeText);
To transaform back:
TransformerFactory tFactory = TransformerFactory.newInstance();
Transformer transformer = tFactory.newTransformer();
DOMSource domSource = new DOMSource(document);
//to print the string in sysout, System.out
StreamResult streamResult = new StreamResult(System.out);
transformer.transform(domSource, streamResult );
To get the result in String:
DOMSource source = new DOMSource(document);
ByteArrayOutputStream outStream = new ByteArrayOutputStream();
StreamResult result = new StreamResult(outStream);
transformer.transform(source, result);
String resultString = new String( outStream.toByteArray());
System.out.println(resultString);
You have a choice of tree models in Java - DOM, XOM, JDOM, DOM4J. Many people (including Singh above) use DOM by default because it is included in the JDK, but it's probably the worst of the bunch, largely because it's the oldest (it was invented before namespaces came along), and because it tries to do too much (HTML, event handling etc, as well as XML). I'd suggest using JDOM2. It shouldn't be hard if you look at the Javadoc for you to find the method that builds a JDOM2 document from an input stream.
Java has a ton of libraries for working with XML. In addition to the many classes that work with XML included with the standard Java installation, there are lots of other open source libraries available. Here are a few options. Take a look at the docs and see which one meets your needs:
The XStream Library is very fast and easy to use. I've used it for XML serialization and I'm very happy with it. If you would rather not use an extrenal library, then try
the javax.xml.parsers.DocumentBuilder class that is demonstrated here
If you want to parse a String str to Document in Java, you can do following:
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = dbf.newDocumentBuilder();
InputStream is = new ByteArrayInputStream(str.getBytes("UTF-8"));
return docBuilder.parse(is);
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!!
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!!
Try the XslCompiledTransform class.
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.
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.
This question already has answers here:
How can I remove the BOM from XmlTextWriter using C#?
(2 answers)
Closed 7 years ago.
I'm opening an existing XML file with C#, and I replace some nodes in there. All works fine. Just after I save it, I get the following characters at the beginning of the file:
 (EF BB BF in HEX)
The whole first line:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
The rest of the file looks like a normal XML file.
The simplified code is here:
XmlDocument doc = new XmlDocument();
doc.Load(xmlSourceFile);
XmlNode translation = doc.SelectSingleNode("//trans-unit[#id='127']");
translation.InnerText = "testing";
doc.Save(xmlTranslatedFile);
I'm using a C# Windows Forms application with .NET 4.0.
Any ideas? Why would it do that? Can we disable that somehow? It's for Adobe InCopy, and it does not open it like this.
UPDATE:
Alternative Solution:
Saving it with the XmlTextWriter works too:
XmlTextWriter writer = new XmlTextWriter(inCopyFilename, null);
doc.Save(writer);
It is the UTF-8 BOM, which is actually discouraged by the Unicode standard:
http://www.unicode.org/versions/Unicode5.0.0/ch02.pdf
Use of a BOM is neither required nor
recommended for UTF-8, but may be
encountered in contexts where UTF-8
data is converted from other encoding
forms that use a BOM or where the BOM
is used as a UTF-8 signature
You may disable it using:
var sw = new IO.StreamWriter(path, new System.Text.UTF8Encoding(false));
doc.Save(sw);
sw.Close();
It's a UTF-8 Byte Order Mark (BOM) and is to be expected.
You can try to change the encoding of the XmlDocument. Below is the example copied from MSDN
using System; using System.IO; using System.Xml;
public class Sample {
public static void Main() {
// Create and load the XML document.
XmlDocument doc = new XmlDocument();
string xmlString = "<book><title>Oberon's Legacy</title></book>";
doc.Load(new StringReader(xmlString));
// Create an XML declaration.
XmlDeclaration xmldecl;
xmldecl = doc.CreateXmlDeclaration("1.0",null,null);
xmldecl.Encoding="UTF-16";
xmldecl.Standalone="yes";
// Add the new node to the document.
XmlElement root = doc.DocumentElement;
doc.InsertBefore(xmldecl, root);
// Display the modified XML document
Console.WriteLine(doc.OuterXml);
}
}
As everybody else mentioned, it's Unicode issue.
I advise you to try LINQ To XML. Although not really related, I mention it as it's super easy compared to old ways and, more importantly, I assume it might have automatic resolutions to issues like these without extra coding from you.