C# Get Microsoft ReportViewer to load XDocument contents - c#

I have an Xdocument object which is populated with xml (the definition for a report -rdl). I would like to give the contents of this XDocument to the report viewer.
this.reportViewer1.LocalReport.LoadReportDefinition();
LoadReportDefinition only seems to take either TextReader or FileStream arguments....but my report definition is loaded within my XDocument? How can I stream the contents of my XDocument?

You can use the StringReader class like so:
using (var textReader = new StringReader(xDocument.ToString()))
{
this.reportViewer1.LocalReport.LoadReportDefinition(textReader);
}
Or alternatively use a Stream:
using (var stream = new MemoryStream())
{
xDocument.Save(stream);
stream.Position = 0;
this.reportViewer1.LocalReport.LoadReportDefinition(stream);
}

Related

Reading XML file from website from console application

What I want to accomplish is reading an xml file from a website (http://xml.buienradar.nl/). I have been reading about what to use, but I can't see the forest for the trees! Should I be using WebRequest, or XmlDocument, or XDocument, or XmlReader, or XmlTextReader, or? I read that XmlDocument and XDocument read the whole file into memory, and XmlReader doesn't. But is that a problem in this case? What if indeed the xml file is huge?
Can someone help me find a way?
Thanks!
To read huge XML without loading all of it into memory, you can use XmlReader class. But please note that this method requires more code than XDocument or even XmlDocument solution.
var h = WebRequest.CreateHttp("http://xml.buienradar.nl/");
using (var r = h.GetResponse())
using (var resp = r.GetResponseStream())
using (var sr = new StreamReader(resp))
using (var xr = new XmlTextReader(sr))
{
while (xr.Read())
{
// doing something with xr
// for example print it's current node value
Console.WriteLine(xr.Value);
}
}
If you want to test for large XML file, you can try XML from http://www.ins.cwi.nl/projects/xmark/Assets/standard.gz.
It is over 30 MB gzipped. With this method, XML processing don't require much memory, it even don't wait for whole file to finished downloading.
Test code:
var h = WebRequest.CreateHttp("http://www.ins.cwi.nl/projects/xmark/Assets/standard.gz");
using (var r = h.GetResponse())
using (var resp = r.GetResponseStream())
using (var decompressed = new GZipStream(resp, CompressionMode.Decompress))
using (var sr = new StreamReader(decompressed))
using (var xr = new XmlTextReader(sr))
{
while (xr.Read())
{
// doing something with xr
// for example print it's current node value
Console.WriteLine(xr.Value);
}
}
XmlTextReader provides a faster mechanism for reading xml.
string url="http://xml.buienradar.nl/";
XmlTextReader xml=new XmlTextReader(url);
while(xml.Read())
{
Console.WriteLine(xml.Value);
}

How to use XmlDocument object instead of reading XML file from drive?

I didn't know that I can use XSD schema to serialize received XML file. I used xsd.exe to generate cs class from XSD file and now I need to use that class to get data in class properties but I miss one thing and I need help.
This is the code:
private void ParseDataFromXmlDocument_UsingSerializerClass(XmlDocument doc)
{
XmlSerializer ser = new XmlSerializer(typeof(ClassFromXsd));
string filename = Path.Combine("C:\\myxmls\\test", "xmlname.xml");
ClassFromXsdmyClass = ser.Deserialize(new FileStream(filename, FileMode.Open)) as ClassFromXsd;
if (myClass != null)
{
// to do
}
...
Here I use XML file from drive. And I want to use this XmlDocument from parameter that I passed in. So how to adapt this code to use doc instead XML from drive?
You could write the XmlDocument to a MemoryStream, and then Deserialize it like you already did.
XmlDocument doc = new XmlDocument();
ClassFromXsd obj = null;
using (var s = new MemoryStream())
{
doc.Save(s);
var ser = new XmlSerializer(typeof (ClassFromXsd));
s.Seek(0, SeekOrigin.Begin);
obj = (ClassFromXsd)ser.Deserialize(s);
}

Assembly load XML document from memorystream C#

I have a database and I convert it to XML document like this:
XmlDocument _XMLDoc = new XmlDocument();
_XMLDoc.LoadXml(dataset.GetXml());
XML document is in memory and I need to read the assembly. So far I can only read the assembly if the file is saved to disk like this:
using (var stream= Assembly.GetExecutingAssembly().GetManifestResourceStream("_XMLDoc.xml"))
{
...
}
How can I modify my code so I can read the assembly from memorystream?
Try the following:
var _XMLDoc = new XmlDocument();
_XMLDoc.LoadXml(dataset.GetXml());
var byteArray = Encoding.ASCII.GetBytes(_XMLDoc.OuterXml);
using (var stream = new MemoryStream(byteArray))
{
// ProcessStream(stream);
}

getting "Stream Was Not Writable" while saving an XML document that I read via a stream from a zip file

I have a zip file that contains an xml file,
I'm Loading this xml file to an xml document without having to extract the file.
this is done via a stream.
after doing so, I'm modifying the inner text of some nodes.
The Problem is that I'm getting the previous mentioned exception after trying to save the stream, here's the code:
(I'm using DotNetZip here)
ZipFile zipFile = ZipFile.Read(zipPath); // the path is my desktop
foreach (ZipEntry entry in zipFile)
{
if (entry.FileName == "myXML.xml")
{
//creating the stream and loading the xml doc from the zip file:
Stream stream = zipFile[entry.FileName].OpenReader();
XmlReader xReader = XmlReader.Create(stream);
XmlDocument xDoc = new XmlDocument();
xDoc.Load(xReader);
//changing the inner text of the doc nodes:
xDoc.DocumentElement.SelectSingleNode("Account/Name").InnerText = "VeXe";
xDoc.DocumentElement.SelectSingleNode("Account/Money").InnerText = "Million$";
xDoc.Save(stream); // here's where I got the exception.
break;
}
}
I'm not a pro coder, but instead of xDoc.Save(stream); I noticed that it could also take a XmlWriter as a parameter, so I tried making an instance of the XmlWriter immediately after instantiating the XmlReader ..
I tried doing this: xDoc.Save(XmlWriter)
I got an exception saying something like: "Cannot Write After Reading"
how can I successfully save the xDoc ?
ADDED:
I had an idea of saving the xml file in some other place, like a temp folder or something
then adding that saved file in the zip overwriting the old one, then deleting the xml file in the temp ..
but that's not what i want, I want to deal directly with the zip file, in and out, no third parties.
You're attempting to write to the same Stream you've opened it with. You cannot do that.
Perhaps try something like this:
ZipFile zipFile = ZipFile.Read(zipPath); // the path is my desktop
foreach (ZipEntry entry in zipFile)
{
if (entry.FileName == "myXML.xml")
{
//creating the stream and loading the xml doc from the zip file:
using (Stream stream = zipFile[entry.FileName].OpenReader()) {
XmlReader xReader = XmlReader.Create(stream);
XmlDocument xDoc = new XmlDocument();
xDoc.Load(xReader);
}
//changing the inner text of the doc nodes:
xDoc.DocumentElement.SelectSingleNode("Account/Name").InnerText = "VeXe";
xDoc.DocumentElement.SelectSingleNode("Account/Money").InnerText = "Million$";
using (StreamWriter streamWriter = new StreamWriter(pathToSaveTo)) {
xDoc.Save(streamWriter);
break;
}
}
}
A quick look at the docs leads me to believe that you should do it something like this:
using(ZipFile zipFile = ZipFile.Read(zipPath))
foreach (ZipEntry entry in zipFile)
{
if (entry.FileName == "myXML.xml")
{
XmlDocument xDoc = new XmlDocument();
//creating the stream and loading the xml doc from the zip file:
using(Stream stream = zipFile[entry.FileName].OpenReader())
using(XmlReader xReader = XmlReader.Create(stream))
{
xDoc.Load(xReader);
}
//changing the inner text of the doc nodes:
xDoc.DocumentElement.SelectSingleNode("Account/Name").InnerText = "VeXe";
xDoc.DocumentElement.SelectSingleNode("Account/Money").InnerText = "Million$";
using(var ms=new MemoryStream())
using(var sw=new StreamWriter(ms))
{
xDoc.Save(sw);
sw.Flush();
ms.Position=0;
zipFile.UpdateEntry(entry.FileName,ms);
}
break;
}
}

Dataset -> XML Document - Load DataSet into an XML Document - C#.Net

I'm trying to read a dataset as xml and load it into an XML Document.
XmlDocument contractHistoryXMLSchemaDoc = new XmlDocument();
using (MemoryStream ms = new MemoryStream())
{
//XmlWriterSettings xmlWSettings = new XmlWriterSettings();
//xmlWSettings.ConformanceLevel = ConformanceLevel.Auto;
using (XmlWriter xmlW = XmlWriter.Create(ms))
{
xmlW.WriteStartDocument();
dsContract.WriteXmlSchema(xmlW);
xmlW.WriteEndDocument();
xmlW.Close();
using (XmlReader xmlR = XmlReader.Create(ms))
{
contractHistoryXMLSchemaDoc.Load(xmlR);
}
}
}
But I'm getting the error - "Root Element Missing".
Any ideas?
Update
When i do xmlR.ReadInnerXML() it is empty. Does anyone know why?
NLV
A few things about the original code:
You don't need to call the write start and end document methods: DataSet.WriteXmlSchema produces a complete, well-formed xsd.
After writing the schema, the stream is positioned at its end, so there's nothing for the XmlReader to read when you call XmlDocument.Load.
So the main thing is that you need to reset the position of the MemoryStream using Seek. You can also simplify the whole method quite a bit: you don't need the XmlReader or writer. The following works for me:
XmlDocument xd = new XmlDocument();
using(MemoryStream ms = new MemoryStream())
{
dsContract.WriteXmlSchema(ms);
// Reset the position to the start of the stream
ms.Seek(0, SeekOrigin.Begin);
xd.Load(ms);
}
XmlDocument contractHistoryXMLSchemaDoc = new XmlDocument();
using (MemoryStream ms = new MemoryStream())
{
dsContract.WriteXml(ms);
ms.Seek(0, SeekOrigin.Begin);
using(XmlReader xmlR = XmlReader.Create(ms))
{
contractHistoryXMLSchemaDoc.Load(xmlR);
}
}
All you really need to do is to call contractHistoryXMLSchemaDoc.Save(ms). That will put the xml into the MemoryStream.
XmlDocument contractHistoryXMLSchemaDoc = new XmlDocument();
using (MemoryStream ms = new MemoryStream())
{
contractHistoryXMLSchemaDoc.Save(ms);
ms.Flush();
}
Here you go.
If from the naming convention of your variables, (not though the question you asked, which appears to change...), you need to load the XML scema of the data set into the XML document that you named with schema, below is the code to load schema of the dataset into an XMLDocument.
I want the schema of the dataset in a separate XML document. – NLV Apr 19 '10 at 12:01
Answer:
XmlDocument contractHistoryXMLSchemaDoc = new XmlDocument();
using (MemoryStream ms = new MemoryStream())
{
dsContract.WriteXmlSchema(ms);
ms.Seek(0, SeekOrigin.Begin);
contractHistoryXMLSchemaDoc.Load(ms);
}
If you are looking for how to load the dataset table data into an XML document (note I removed the word Schema from the XMLDocument variable name)
Your Question:
Sorry, i dont get you. I need to get the xml of that dataset into an xml document. – NLV Apr 19 '10 at 11:56
Answer:
XmlDocument contractHistoryXMLDoc = new XmlDocument();
using (MemoryStream ms = new MemoryStream())
{
dsContract.WriteXml(ms,XmlWriteMode.IgnoreSchema);
ms.Seek(0, SeekOrigin.Begin);
contractHistoryXMLDoc.Load(ms);
}
If you want the Schema and data set in separate documents, the code is above.
If you want just the schema or just the data in and xml document, use the above bit of code that pertains to your question.
If you want both the XML Schema and the Data in the same XMLDocument, then use this code.
XmlDocument contractHistoryXMLDoc = new XmlDocument();
using (MemoryStream ms = new MemoryStream())
{
dsContract.WriteXml(ms,XmlWriteMode.WriteSchema);
ms.Seek(0, SeekOrigin.Begin);
contractHistoryXMLDoc.Load(ms);
}
Your Question:
But I'm getting the error - "Root Element Missing".
Any ideas?
Update
When i do xmlR.ReadInnerXML() it is empty. Does anyone know why?
NLV
Answer:
There are underlying issues in your code in the way you think it is working, which means it is not really creating the XMLSchema and XmlData (dsContract), which is why you are seeing a blank XMLDocument.
It would probably help you to fully explain what you wish, and then not reply to everyone using partial sentences of which are misunderstood and your having to keep replying with more partial sentences.

Categories

Resources