I am calling oracle package, to get xml file from the package into oracleDataReader. How can i load that into xmldocument?
Here is the code:
OracleDataReader reader = new OracleDataReader();
//calling package here and reading xml file into reader...
reader = cmd.ExecuteReader();
while(reader.Read())
{
XmlDocument doc = new XmlDocument();
doc.LoadXml("what should i enter here to add the reader xml file???");
}
try
doc.LoadXml(reader.GetString(0));
IF the above does not work for you please provide information on the statement that is run by cmd and the DB structure/field definition etc.
Related
I'm having trouble saving my XML file after I have called load. This function is called twice - once when "toSave" is set to false, and then the second time is when it is set to true. On the second time round, the save causes an exception. I tried adding a Dispose and Close call to the XMLReader but nothing seems to help. Here is the code:
// Check if the file exists
if (File.Exists(filePath))
{
try
{
// Load the file
XmlReaderSettings readerSettings = new XmlReaderSettings();
readerSettings.IgnoreComments = true;
XmlReader reader = XmlReader.Create(filePath, readerSettings);
XmlDocument file = new XmlDocument();
file.Load(reader);
XmlNodeType type;
type = file.NodeType;
if (toSave)
ModifyXMLContents(file.FirstChild.NextSibling, null);
else
PopulateNode(file.FirstChild.NextSibling, null);
// Save if we need to
if (toSave)
file.Save(filePath);
reader.Dispose();
reader.Close();
}
catch (Exception ex)
{
// exception is: "The process cannot access the file d:\tmp\10.51.15.2\Manifest.xml" because it is being used by another process
Console.WriteLine(ex.Message);
}
}
Any help would be greatly appreciated.
The XmlReader you created is still open when you try to save it, and hence it is locking the file and preventing the save.
Once loaded into the XmlDocument, you don't need the reader anymore, so you can close/dispose it before you attempt the save and then the save should work.
For example:
XmlReaderSettings readerSettings = new XmlReaderSettings();
readerSettings.IgnoreComments = true;
XmlDocument file = new XmlDocument();
using (XmlReader reader = XmlReader.Create(filePath, readerSettings))
file.Load(reader);
/* do work with xml document */
if (save)
file.Save(filePath);
For me this was caused by the file being written out into a directory with MANY (100k) other files. Once I cleared out all the other files the problem went away. NTFS appears to get cranky with very large numbers of files in a single folder.
What is the best way to serialize a large collection of objects?
I need to serialize 10 millions of collections from the database to xml.
I always have OutOfMemoryException.
Can you help me with it?
You need to do this in a Read loop one by one. Read one from DB and insert one to XML file by using XmlTextWriter.
Something like below should work for your case.
using (var xml = new XmlTextWriter ("filename", Encoding.UTF8))
{
xml.WriteStartElement ("container_name");
var cmd = new SqlCommand ("your query", dbConnection);
using (var reader = cmd.ExecuteReader ())
{
while (reader.Read ())
{
//
// Read from DB write to xml
//
}
}
xml.WriteEndElement (); // Close your container
}
For XmlTextWriter reference check MSDN
In C# am trying to check to see if an XML file is created, if not create the file and then create the xml declaration, a comment and a parent node.
When I try to load it, it gives me this error:
"The process cannot access the file 'C:\FileMoveResults\Applications.xml' because it is being used by another process."
I checked the task manager to ensure it wasn't open and sure enough there were no open applications of it. Any ideas of what's going on?
Here is the code I am using:
//check for the xml file
if (!File.Exists(GlobalVars.strXMLPath))
{
//create the xml file
File.Create(GlobalVars.strXMLPath);
//create the structure
XmlDocument doc = new XmlDocument();
doc.Load(GlobalVars.strXMLPath);
//create the xml declaration
XmlDeclaration xdec = doc.CreateXmlDeclaration("1.0", null, null);
//create the comment
XmlComment xcom = doc.CreateComment("This file contains all the apps, versions, source and destination paths.");
//create the application parent node
XmlNode newApp = doc.CreateElement("applications");
//save
doc.Save(GlobalVars.strXMLPath);
Here is the code I ended up using to fix this issue:
//check for the xml file
if (!File.Exists(GlobalVars.strXMLPath))
{
using (XmlWriter xWriter = XmlWriter.Create(GlobalVars.strXMLPath))
{
xWriter.WriteStartDocument();
xWriter.WriteComment("This file contains all the apps, versions, source and destination paths.");
xWriter.WriteStartElement("application");
xWriter.WriteFullEndElement();
xWriter.WriteEndDocument();
}
File.Create() returns a FileStream that locks the file until it's closed.
You don't need to call File.Create() at all; doc.Save() will create or overwrite the file.
I would suggest something like this:
string filePath = "C:/myFilePath";
XmlDocument doc = new XmlDocument();
if (System.IO.File.Exists(filePath))
{
doc.Load(filePath);
}
else
{
using (XmlWriter xWriter = XmlWriter.Create(filePath))
{
xWriter.WriteStartDocument();
xWriter.WriteStartElement("Element Name");
xWriter.WriteEndElement();
xWriter.WriteEndDocument();
}
//OR
XmlDeclaration xdec = doc.CreateXmlDeclaration("1.0", null, null);
XmlComment xcom = doc.CreateComment("This file contains all the apps, versions, source and destination paths.");
XmlNode newApp = doc.CreateElement("applications");
XmlNode newApp = doc.CreateElement("applications1");
XmlNode newApp = doc.CreateElement("applications2");
doc.Save(filePath); //save a copy
}
The reason your code is currently having problems is because of: File.Create creates the file and opens the stream to the file, and then you never make use of it (never close it) on this line:
//create the xml file
File.Create(GlobalVars.strXMLPath);
if you did something like
//create the xml file
using(Stream fStream = File.Create(GlobalVars.strXMLPath)) { }
Then you would not get that in use exception.
As a side note XmlDocument.Load will not create a file, only work with an already create one
You could create a stream, setting the FileMode to FileMode.Create and then use the stream to save the Xml to the path specified.
using (System.IO.Stream stream = new System.IO.FileStream(GlobalVars.strXMLPath, FileMode.Create))
{
XmlDocument doc = new XmlDocument();
...
doc.Save(stream);
}
I am simply trying to load a dataset and output it on a webpage as XML with the schema being written as well. I have been researching to find a way to achieve this without any luck.
The code I am using is:
string str =
"SELECT Name,Members,MaxLvl,Faction,Government,Score FROM dim5orgs where faction =
'Omni' order by Score DESC";
// Connection string for a typical local MySQL installation
string cnnString = "Server=xxxxxxxnet;Port=3306;Database=xxx;Uid=xxxxx;Pwd=xxxx";
// Create a connection object and data adapter
MySqlConnection cnx = new MySqlConnection(cnnString);
MySqlDataAdapter adapter = new MySqlDataAdapter();
// Create a SQL command object
string cmdText = str;
MySqlCommand cmd = new MySqlCommand(cmdText, cnx);
// Create a fill a Dataset
DataSet ds = new DataSet();
adapter.SelectCommand = cmd;
adapter.Fill(ds);
StringWriter sw = new StringWriter();
ds.WriteXml(sw,XmlWriteMode.WriteSchema);
string result = sw.ToString();
Response.Write(result);
Right now I am getting output like:
Punk732220OmniRepublic1644786805740
Paradise754220OmniDepartment1633903815782
I would like the output to be in proper XML form somehow using the column names in the dataset.
Like:
<data>
<name>Punk</name>
<members>732</members>
<Maxlvl>220</MaxLvl>...etc
</data>
I would like to be in proper XML form, with the XML headers written properly.
Thank you.
Look into the documentation of the XmlSerializer Class. I think you could use it something like this:
StreamWriter streamWriter = new StreamWriter(fileLocation);
XmlSerializer xml = new System.Xml.Serialization.XmlSerializer(ds.GetType());
xml.Serialize(streamWriter, ds);
streamWriter.Close();
I have not tried it with DataSets so I'm not sure.
When you say "I am getting output like", does that mean you are seeing that in your webpage, or that is what "result" contains when you debug the program?
If the former, you are probably missing setting the response type:
Response.ContentType = "text/xml";
and optionally the encoding:
Response.ContentEncoding = System.Text.Encoding.UTF8;
before you write your response.
EDIT: Also, make sure you are not returning any html from your page template or master page (assuming you are using .aspx files). You can check this by looking at your page source in your browser (right click and "view source" in IE). Apologies if this teaching you to suck eggs, from your question I didn't know if you have already checked these things or not.
Edit 2: I've tested your code, and if you set the response ContentType to text/xml it works for me.
consider my source file looks like this.
<Content xmlns="uuid:4522eb85-0a47-45f9-8e2b-1x82c78xx920">
<first>Hello World.This is Fisrt field</first>
<second>Hello World.This is second field</second>
</Content>
I want to write a code, which read this xml document from a location and display it as string.
say name of the xml file is helloworld.xml.
Location: D:\abcd\cdef\all\helloworld.xml.
I have tried the following, but i was unable to do it.
XmlDocument contentxml = new XmlDocument();
contentxml.LoadXml(#"D:\abcd\cdef\all\helloworld.xml");
Response.Write("<BR>" + contentxml.ToString());
Response.write is displaying nothing. Correct me if i missed any thing. Its not creating any component and error is coming.
I have also tried this,
XmlDocument contentxml = new XmlDocument();
try
{
contentxml.LoadXml(#"D:\abcd\cdef\all\helloworld.xml");
}
catch (XmlException exp)
{
Console.WriteLine(exp.Message);
}
StringWriter sw = new StringWriter();
XmlTextWriter xw = new XmlTextWriter(sw);
contentxml.WriteTo(xw);
Response.Write("<BR>" + sw.ToString());
But i did not find the any output.
I want to read a XML file from a location and display it as it is as string.
Can anyone help on this.
Thank you,
Muzimil.
You need the OuterXml property:
Response.Write("<BR>" + contentxml.OuterXml);
Also you are loading a file not xml so use
contentxml.Load(#"D:\abcd\cdef\all\helloworld.xml");
instead of
contentxml.LoadXml(#"D:\abcd\cdef\all\helloworld.xml");
Do you really have to deserialize the XML at all? Why not just read it as a text file? Something like..
String text = File.ReadAllText(#"D:\abcd\cdef\all\helloworld.xml");
Response.Write(text);
With appropriate error handling obviously..
I would try using the XDocument class:
//load the document from file
var doc = XDocument.Load("..."); //== path to the file
//write the xml to the screen
Response.Write(doc.ToString());
If you want to use an XmlDocument instead, you would want to use Load instead LoadXml.
If you want to simply write a file to the output, you can do Response.WriteFile.
try this
XmlTextReader reader = new XmlTextReader (#"D:\abcd\cdef\all\helloworld.xml");
while (reader.Read())
{
Console.WriteLine(reader.Name);
}
Console.ReadLine();
String text = File.ReadAllText(Server.MapPath("~/App_Data/sample.xml"));
txtData.Text = text;