What's the non-deprecated alternative to XmlDataDocument and XslTransform? - c#

I am modifying some legacy code to try to eliminate warnings. XmlDataDocument and XslTransform both generate warnings that they are obsolete. In the case of XslTransform the suggested replacement is XslCompiledTransform, but no replacement is suggested for XmlDataDocument.
How can I change this code to eliminate warnings in .NET 4:
var xmlDoc = new System.Xml.XmlDataDocument(myDataSet);
var xslTran = new System.Xml.Xsl.XslTransform();
xslTran.Load(new XmlTextReader(myMemoryStream), null, null);
var sw = new System.IO.StringWriter();
xslTran.Transform(xmlDoc, null, sw, null);

XDocument doc = new XDocument();
using (XmlWriter xw = doc.CreateWriter())
{
myDataSet.WriteXml(xw);
xw.Close();
}
XslCompiledTransform proc = new XslCompiledTransform();
using (XmlReader xr = XmlReader.Create(myMemoryStream))
{
proc.Load(xr);
}
string result;
using (StringWriter sw = new StringWriter())
{
proc.Transform(doc.CreateNavigator(), null, sw); // needs using System.Xml.XPath;
result = sw.ToString();
}
should do I think. Of course I have only used that MemoryStream for loading the stylesheet and the StringWriter for sending the transformation result to as you code snippet used those. Usually there are other input sources or output destinations like files, or streams or Textreader.

XMLDocument is really your main option. I'm not 100% sure what you're trying to do with the code block you've posted, but you can give something like this a shot:
public void DoThingsWithXml()
{
string strXdoc = src.GetTheXmlString(); // however it is you do it
XmlDocument xdoc = new XmlDocument();
xdoc.LoadXml(strXdoc);
// The other things you need to do
}

Related

How to transform XML two times using XSLT?

I have to transform .xml two times with different .xslt files and I know how to transform it once, but don't have idea, how to repeat it, because when I my output was something like html string and i changed my code, by using XmlWriter instead of StringWriter (commented), but it generates an empty Xml so it can't be transferred again.
public static HtmlString RenderXml(this HtmlHelper helper, string xml, string transformXsltPath, string xsltPath)
{
xml = System.IO.File.ReadAllText(("C:/Users/Student/Documents/Visual Studio 2010/Projects/MvcApplication2/MvcApplication2/schemat.xsd"));
XsltArgumentList args = new XsltArgumentList();
XslCompiledTransform t = new XslCompiledTransform();
t.Load(transformXsltPath);
XmlReaderSettings settings = new XmlReaderSettings();
settings.DtdProcessing = DtdProcessing.Parse;;
using (XmlReader reader = XmlReader.Create(new StringReader(xml), settings))
{
//StringWriter writer = new StringWriter();
XmlWriter writer = XmlWriter.Create(new StringWriter());
t.Transform(reader, args, writer);
XslCompiledTransform t2 = new XslCompiledTransform();
t2.Load(xsltPath);
XmlReader reader2 = XmlReader.Create(new StringReader(writer.ToString()), settings);
StringWriter writer2 = new StringWriter();
t2.Transform(reader2, args, writer2);
HtmlString htmlString = new HtmlString(writer2.ToString());
return htmlString;
}
}

XSLT transformation for Word

I'm writing a web service in .NET C# that takes in an object, converts it to xml, applies an XSLT template, runs the transformation, and returns an MS work file.
Here is the code for the function:
public static HttpResponseMessage Transform(object data)
{
var response = new HttpResponseMessage(HttpStatusCode.OK);
StringWriter stringWriter = new StringWriter();
XmlWriter xmlWriter = XmlWriter.Create(stringWriter);
var applicationDirectory = AppDomain.CurrentDomain.BaseDirectory;
var xsltPath = applicationDirectory + #"\Reporting\Files\Template.xslt";
var templatePath = applicationDirectory + #"\Reporting\Files\Template.docx";
var xmlObject = new System.Xml.Serialization.XmlSerializer(data.GetType());
MemoryStream stream;
using (stream = new MemoryStream())
{
var sw = new StreamWriter(stream);
xmlObject.Serialize(stream, data);
stream.Position = 0;
XslCompiledTransform transform = new XslCompiledTransform();
transform.Load(xsltPath);
using (XmlReader xmlReader = XmlReader.Create(stream))
{
transform.Transform(xmlReader, xmlWriter);
XmlDocument newWordContent = new XmlDocument();
newWordContent.LoadXml(stringWriter.ToString());
var outputPath = applicationDirectory + #"\Reporting\Temp\temp.docx";
System.IO.File.Copy(templatePath, outputPath, true);
using (WordprocessingDocument output = WordprocessingDocument.Open(outputPath, true))
{
Body updatedBodyContent = new Body(newWordContent.DocumentElement.InnerXml);
output.MainDocumentPart.Document.Body = updatedBodyContent;
output.MainDocumentPart.Document.Save();
}
response.Content = new StreamContent(new FileStream(outputPath, FileMode.Open, FileAccess.Read));
response.Content.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment");
response.Content.Headers.ContentDisposition.FileName = outputPath;
}
}
return response;
}
When I make a request, it gives me a word file without the data.
I put a breakpoint at using (XmlReader xmlReader = XmlReader.Create(stream)).
After running that line, xmlReader has a value of {None}.
I'm also trying to avoid creating an XML file for efficiency(Hence MemoryStream).
Any idea why this isn't working? And is there a better way of accomplishing this?
Thanks,
Gerson
What happens if you change this:
Body updatedBodyContent = new Body(newWordContent.DocumentElement.InnerXml);
to this:
Body updatedBodyContent = new Body(newWordContent.InnerXml);
or this:
Body updatedBodyContent = new Body(newWordContent.DocumentElement.OuterXml);
The way you have it there would cause the outer element of the transformed XML to be omitted, and I doubt that's what you want (though can't say for sure because you've shown us neither the input XML or the XSLT.

C# XSLT in memory transformation

I am currently running a live 'in-memory' XSLT transformation using the following code
XmlDocument XmlDoc = new XmlDocument();
XmlDoc.LoadXml(DS.GetXml());
XslCompiledTransform XsltTranformation = new XslCompiledTransform();
XsltTranformation.Load(#"C:\Users\maskew\Desktop\XSLTMapping.xsl");
Stream XmlStream = new MemoryStream();
XmlDoc.Save(XmlStream); //Stream is still blank after this line
XmlReader XmlRdr = XmlReader.Create(XmlStream);
MemoryStream stm = new MemoryStream();
XsltTranformation.Transform(XmlRdr, null, stm);
stm.Position = 1;
StreamReader sr = new StreamReader(stm);
string Output = sr.ReadToEnd();
Output = Output.Substring(2);
XmlDoc.LoadXml(Output);
XmlWriter XmlWrtr = XmlWriter.Create(#"C:\Users\maskew\Desktop\XmlMapping.xml");
XmlDoc.WriteTo(XmlWrtr);
XmlWrtr.Flush();
XmlWrtr.Close();
However, when I move the file from XmlDocument to MemoryStream in line 6 the stream contains nothing when checked and thus stopping the whole program from running.
Does anyone have any idea why this would be occuring?
UPDATED: The stream is containing information now, however the XmlReader object is receiving none of it still.
Try a simplyfying
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.PreserveWhitespace = true;
xmlDoc.LoadXml(DS.GetXml());
// Create a writer for writing the transformed file.
XmlWriter writer = XmlWriter.Create(#"C:\Users\maskew\Desktop\XmlMapping.xml");
// Create and load the transform with script execution enabled.
XslCompiledTransform transform = new XslCompiledTransform();
XsltSettings settings = new XsltSettings();
settings.EnableScript = true;
transform.Load(#"C:\Users\maskew\Desktop\XSLTMapping.xsl", settings, null);
// Execute the transformation.
transform.Transform(xmlDoc, writer);
Try flushing and resetting the stream:
XmlDoc.Save(XmlStream);
XmlStream.Flush();
XmlStream.Position = 0;
XmlReader XmlRdr = XmlReader.Create(XmlStream);
Stream XmlStream = new MemoryStream();
How there can be something in it ? You are constructing an empty memoryStream...
EDIT :
You should try to clarify it by using the 'using' instruction (http://msdn.microsoft.com/fr-fr/library/yh598w02). Basically, class like StreamReader, MemeryStream, etc.. implement the IDisposable interface. If you wrap them with using, it will dispose the object automatically for you.

format the xml output

I am using this method to transform an object to XML:
protected XmlDocument SerializeAnObject(object obj)
{
XmlDocument doc = new XmlDocument();
DataContractSerializer serializer = new DataContractSerializer(obj.GetType());
MemoryStream stream = new MemoryStream();
try
{
serializer.WriteObject(stream, obj);
stream.Position = 0;
doc.Load(stream);
return doc;
}
finally
{
stream.Close();
stream.Dispose();
}
}
Eventually I get something like:
<CaCT>
<CTC i:nil="true" xmlns="http://schemas.datacontract.org/2004/07/a.b.BusinessEntities.InnerEntities" />
<CTDescr xmlns="http://schemas.datacontract.org/2004/07/a.b.BusinessEntities.InnerEntities">blabla</CTDescr>
<CaId>464</CaId>
</CaCT>
How can I get rid of the i:nil="true" and the xmlns="http://schemas.datacontract.org/2004/07/a.b.BusinessEntities.InnerEntities"?
Personally I've always found that hand-written XML serialization with LINQ to XML works well. It's as flexible as you want, you can make it backward and forward compatible in whatever way you want, and obviously you don't end up with any extra namespaces or attributes that you don't want.
Obviously it becomes more complicated the more complicated your classes are, but I've found it works very well for simple classes. It's at least an alternative to consider.
protected string SerializeAnObject(object obj)
{
XmlSerializerNamespaces xmlNamespaces = new XmlSerializerNamespaces();
xmlNamespaces.Add("", "");
XmlWriterSettings writerSettings = new XmlWriterSettings();
writerSettings.OmitXmlDeclaration = true;
XmlSerializer serializer = new XmlSerializer(obj.GetType());
using (MemoryStream ms = new MemoryStream())
{
using (XmlWriter stream = XmlWriter.Create(ms, writerSettings))
{
serializer.Serialize(stream, obj, xmlNamespaces);
return Encoding.UTF8.GetString(ms.ToArray());
}
}
}

XslCompiledTransform output as XPathDocument

I am trying to use a XslCompiledTransform, and use the output as a XPathDocument.
Any Ideas?
Mr. Jones's answer was very helpful for me, but I found that the last line didn't work. I ended up doing this:
XslCompiledTransform xsl = new XslCompiledTransform();
xsl.Load(filePath);
StringWriter stringWriter = new StringWriter();
XmlWriter xmlWriter = XmlTextWriter.Create(stringWriter);
xsl.Transform(xPathDoc, xmlWriter);
String newXml = stringWriter.ToString();
StringReader stringReader = new StringReader(newXml);
xPathDoc = new XPathDocument(stringReader);
(Here, xPathDoc is an XPathDocument that has already been initialized from an XmlReader.)
Send the transform to an XmlTextWriter based on a StringWriter. Then instance the XPathDocument by retreiving the XML string from the StringWriter.
var sw = new StringWriter();
var xtw = new XmlTextWriter(sw);
myTransform.Transform(myXml, xtw);
var xpd = new XPathDocument(sw.ToString());
Its not the most memory efficient mechanism but will be adequate for most needs. A similar approach would be use a MemoryStream instead of a StringWriter but its a little messy by comparison.
A slightly better form of David M. Anderson's answer is below: it does not suffer from potential resource leaks; otherwise it is the same.
private static XPathDocument TransformToXPathDocument(string styleSheetPath,
IXPathNavigable xPathDoc)
{
var xsl = new XslCompiledTransform();
xsl.Load(styleSheetPath);
using(var stringWriter = new StringWriter())
{
using(XmlWriter xmlWriter = XmlWriter.Create(stringWriter))
{
xsl.Transform(xPathDoc, xmlWriter);
}
using(var reader = new StringReader(stringWriter.ToString()))
{
return new XPathDocument(reader);
}
}
}

Categories