I have a document library named "xsl library" with a bunch of xsl's... and I need to read a file (anyone one) from there so I can use it transform a xml that renders a webpart... the layout out of a webpart is determined by the xsl... how can I do it?
Notes: Enviroment -> Sharepoint 2007
So it looks like you need some server side code:
SPFile xslFile = SPContext.Current.Web.GetFile("/myWeb/myXlsLibrary/myXsl.xsl");
Stream xslStream = xslFile.OpenBinaryStream();
Then you code similar to one provided by Vlad above to make the transformation.
See MSDN for more info on functions used - http://msdn.microsoft.com/en-us/library/microsoft.sharepoint.spweb.getfile.aspx , http://msdn.microsoft.com/en-us/library/microsoft.sharepoint.spfile.openbinarystream.aspx.
XslCompiledTransform proc = new XslCompiledTransform();
proc.Load(XmlReader.Create(new StringReader(stringWithXsltStylesheetCode)));
XmlDocument result = new XmlDocument();
using (XmlWriter xw = result.CreateNavigator().AppendChild())
{
proc.Transform(inputXmlDocument, null, xw);
xw.Close();
}
Related
I am opening existing .docx files from a SharePoint Document Library over the SharePoint web services, and am attempting to attach a new Template to them. The current code for this piece seems to not be doing anything at all.
XNamespace w = "http://schemas.openxmlformats.org/wordprocessingml/2006/main";
OpenXmlPart documentSettingsPart = document.MainDocumentPart.DocumentSettingsPart;
XDocument documentSettingsXDoc = documentSettingsPart.GetXDocument();
documentSettingsPart.AddExternalRelationship("http://schemas.openxmlformats/org/officeDocument/2006/relationships/attachedTemplate", new Uri(_outLibraryTemplate, UriKind.Absolute));
using (XmlWriter xw = XmlWriter.Create(documentSettingsPart.GetStream(FileMode.Create, FileAccess.Write)))
documentSettingsXDoc.Save(xw);
Does anyone have any thoughts as to why this isn't working - and what I need to do to get this going?
This may help. It creates a new docx file from a dotx file.
I modified it a little for my own use - I added the external relationship (a dotm) to an existing file. Unfortunately I can't work out yet if I can easily programatically update the styles without having to actually open the file.
https://web.archive.org/web/20150716111136/http://blogs.msdn.com/b/vsod/archive/2012/02/18/how-to-create-a-document-from-a-template-dotx-dotm-and-attach-to-it-using-open-xml-sdk.aspx
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.
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.
I have modified the title of the question after finding the answer :) :P
I am loading an XML file and an XSL file by a C# program and triggering the XSL transformation .. here is the code for it:
static void Main(string[] args)
{
// Create the XslCompiledTransform and load the stylesheet.
XslCompiledTransform xslt = new XslCompiledTransform();
xslt.Load("input.xsl"); //located in Debug folder
//Load XSL argument list
XsltArgumentList xslArg = new XsltArgumentList();
// Transform the file.
using (XmlWriter w = XmlWriter.Create("output.xml"))
{
xslt.Transform("input.xml", xslArg, w); //located in Debug folder
}
}
The error is I am not able to load XML file.
The XSL file contains some C# code which is meant to calculate the difference between two DateTime strings .. well, I can transform the XML file manually using the same XSL file .. But when I try to trigger the transformation using C# code .. then it says "It can't load XML file"
Here is my (part of) XSL code ..
<span bgcolor="#EEEEEE">
<xsl:variable name="date1" select="//date1"/>
<xsl:variable name="date2" select="//date2"/>
<msxsl:script language="C#" implements-prefix="cs">
<![CDATA[
public string datediff(string date1, string date2) {
DateTime startTime = new DateTime(Convert.ToInt32(date1.Substring(6, 4)), Convert.ToInt32(date1.Substring(0, 2)), Convert.ToInt32(date1.Substring(3, 2)), Convert.ToInt32(date1.Substring(11, 2)), Convert.ToInt32(date1.Substring(14, 2)), Convert.ToInt32(date1.Substring(17, 2)), 0);
DateTime endTime = new DateTime(Convert.ToInt32(date2.Substring(6, 4)), Convert.ToInt32(date2.Substring(0, 2)), Convert.ToInt32(date2.Substring(3, 2)), Convert.ToInt32(date2.Substring(11, 2)), Convert.ToInt32(date2.Substring(14, 2)), Convert.ToInt32(date2.Substring(17, 2)), 0);
return(endTime.Subtract(startTime));
}
]]>
</msxsl:script><br>
<xsl:template match="datediff"><br>
<xsl:element name="{local-name()}"><br>
<xsl:value-of select="cs:datediff($date1, $date2)" /><br>
</xsl:element><br>
</xsl:template><br></span>
Is that, because of script(C# code to calculate date diff..) I am getting this error?By the way C# code runs perfectly when I use some other input XML and XSL files ..
please help me to overcome this error ..
As Steve cooper has mentioned .. you need to enable the XSLT script .. and here is the way to do it:
first define a new settings instance:
var settings = new XsltSettings();
then enable the script
settings.EnableScript = true;
Create the XslCompiledTransform object and load the style sheet, passing in the settings object.
In the MSDN Documentation it says "XSLT scripting is disabled by default. XSLT scripting should be enabled only if you require script support and you are working in a fully trusted environment."
This is probably your problem. Try loading the transform like this;
XslCompiledTransform xslt = new XslCompiledTransform();
// Disable script blocks and the document() function
// if a stylesheet came from an untrusted source
string untrustedUri = #"http://www.untrusted-site.com/meow.xsl";
XmlResolver secureResolver = new XmlSecureResolver(new XmlUrlResolver(), untrustedUri);
xslt.Load(untrustedUri, XsltSettings.Default, secureResolver);
// Enable script blocks and the document() function
// if a trusted stylesheet needs them
xslt.Load(#"C:\MyProject\purr.xsl", XsltSettings.TrustedXslt, new XmlUrlResolver());
You could add some detail to your question, too; can you say how you are able to do it manually? What program or engine are you using? For instance, XMLSpy uses a different transform engine from the .Net framework, so XSL files can be incompatable.
Define the settings variable Enabling Script Mode and then use it in the load process.
var settings = new XsltSettings();
settings.EnableScript = true;
XslCompiledTransform xslt = new XslCompiledTransform();
xslt.Load("input.xsl", settings , null);
It worked for me.
Regards!
I would suggest trying to load the XML file completely separately - I wouldn't be surprised to find that this had nothing at all to do with XSL, and everything to do with it not being able to find the file or something similar.
Try loading the XML file into an XmlDocument and checking that it looks correct. If that works, use the overload accepting an IXPathNavigable as input (XmlDocument implements IXPathNavigable).