How to add XML schema and XML element together in same file? - c#

**
I want to add XML schema and XML element together in same file. Because this xml file we will need to generate through C# based on specific record. So, i am looking some code help how can i write together XMLSchema and XML element in same file and inside same element. Please check attachment.
<Survey>
**Here i want XML schema**
**Here i want XML element**
</Survey>

Working Code Example
SiteSurveyX siteSurveyX = new SiteSurveyX();
XmlTextReader reader = new XmlTextReader("c:\\temp\\TestSiteSchema.xsd");
//siteSurveyX.SurveySchema = XmlSchema.Read(reader, null);
XmlSchema myschema = XmlSchema.Read(reader, null);
string filePath = HelperFunctions.SurveyFilePath + routeName;
////Get all node record from DB
siteSurveyX.Survey = routeService.GetRouteDetailForXML(routeId, Convert.ToString(ddlRoute.Text), chkCurrentInterruption.Checked);
using (FileStream stream = new FileStream(filePath, FileMode.Create, FileAccess.ReadWrite))
{
lblStatus.Text = "Preparing file";
stream.Close();
stream.Dispose();
//Convert record in XML
XmlSerializer serializer = new XmlSerializer(typeof(SiteSurveyX));
using (StreamWriter writer = new StreamWriter(filePath, true))
{
serializer.Serialize(writer, siteSurveyX);
lblStatus.Text = "Ready";
}
}
It's done with this code.

Related

XML file to datagridview c#

I am using an api that returns text in XML that I am saving to an XML file.
Whenever I am trying to display the information to a datagridview. But I get an error saying the file is already open and being used. Here is the code that receives the text, saves it to the XML and tries to display it to the datagrid.
using (WebResponse response = request.GetResponse())
{
using (Stream stream = response.GetResponseStream())
{
using (StreamReader sr99 = new StreamReader(stream))
{
responseContent = sr99.ReadToEnd();
}
}
}
XmlDocument doc = new XmlDocument();
doc.LoadXml(responseContent);
XmlWriterSettings settings = new XmlWriterSettings();
settings.Indent = true;
// Save the document to a file and auto-indent the output.
XmlWriter writer = XmlWriter.Create("ResponseContent.xml", settings);
doc.Save(writer);
XmlReader xmlFile = XmlReader.Create(#"C:\Users\Tyler\Documents\Repo\New Trunk\WalmartSmiles\WalmartSmiles\bin\Debug\ResponseContent.xml", new XmlReaderSettings());
DataSet dataSet = new DataSet();
//Read xml to dataset
dataSet.ReadXml("ResponseContent.xml");
//Pass empdetails table to datagridview datasource
dataGridView1.DataSource = dataSet.Tables["ns2:feed"];
//Close xml reader
xmlFile.Close();
XmlReader xmlFile ;
xmlFile = XmlReader.Create("Product.xml", new XmlReaderSettings());
DataSet ds = new DataSet();
ds.ReadXml(xmlFile);
dataGridView1.DataSource = ds.Tables[0];
Simple way of pass data to dataGridView
Usually when this happens, look for other things in your code that have also opened, read, written, or done anything with that file, and close them!
// Save the document to a file and auto-indent the output.
XmlWriter writer = XmlWriter.Create("ResponseContent.xml", settings);
doc.Save(writer);
writer.Close();

Illegal characters in path error in XML Deserilation

I have got XML response from my client. I can't deserialize the XML as string, it throws an Illegal characters in path error. So now I save the file in temp folder and retrieve that. Is it possible to do the deserialize without saving the XML file first?
string xml = Post();
XmlSerializer deserializer = new XmlSerializer(typeof(Envelope));
TextReader reader = new StreamReader(xml); <-- Illegal characters in path error -->
object obj = deserializer.Deserialize(reader);
Envelope XmlData = (Envelope)obj;
reader.Close();
Edit 1 -
XmlSerializer serializer = new XmlSerializer(typeof(Envelope));
using (TextWriter writer = new StreamWriter(xml)) <-- StringWriter is Possible here? -->
{
serializer.Serialize(writer, XmlData);
}
Instead of a StreamReader, use a StringReader, that takes a string as constructor parameter.
TextReader reader = new StringReader(xml);
For writing, use this:
string output;
XmlSerializer serializer = new XmlSerializer(typeof(Envelope));
using (TextWriter writer = new StreamWriter(xml)) <-- StringWriter is Possible here? -->
{
serializer.Serialize(writer, XmlData);
output = writer.ToString();
}

Why xmlreader can't read something that xmlwriter wrote?

I have the simplest code in the world,
using (XmlWriter writer = XmlWriter.Create(stringWriter))
{
writer.WriteStartDocument();
writer.WriteStartElement("Board");
writer.WriteAttributeString("Rows", mRows.ToString());
writer.WriteAttributeString("Columns", mColumns.ToString());
writer.WriteEndElement();
writer.WriteEndDocument();
}
TextWriter writer1 = new StreamWriter(path);
writer1.Write(stringWriter.toString());
writer1.Close();
Then i write it to a txt file that looks like this:
<?xml version="1.0" encoding="utf-16"?>
<Board Rows="30" Columns="50">
</Board>
Then i do the following :
FileStream str = new FileStream(s.FileName, FileMode.Open);
using(XmlReader reader = XmlReader.Create(stream))
{
reader.Read();
}
And it throws an exception :
"There is no Unicode byte order mark. Cannot switch to Unicode."
I googled the exception and found several workarounds, but i don't understand why i need a work around, i just want to read the xml i wrote.
Can some one please explain what exactly the problem is ?
Should i write something differently in the xml ?
What is the simplest solution to this ?
You're probably not writing to a unicode file which File.WriteAllText or a vanilla FileStream does not do.
Instead use File.OpenWrite or FileStream combined with the StreamWriter(Stream steam, Encoding encoding) constructor to specify unicode.
Sample:
var path = #"C:\Dev\sample.xml";
string xml;
var mRows = 30;
var mColumns = 50;
var options = new XmlWriterSettings { Indent = true };
using (var stringWriter = new StringWriter())
{
using (var writer = XmlWriter.Create(stringWriter, options))
{
writer.WriteStartDocument();
writer.WriteStartElement("Board");
writer.WriteAttributeString("Rows", mRows.ToString());
writer.WriteAttributeString("Columns", mColumns.ToString());
writer.WriteEndElement();
writer.WriteEndDocument();
}
xml = stringWriter.ToString();
}
if(File.Exists(path))
File.Delete(path);
using(var stream = File.OpenWrite(path))
using(var writer = new StreamWriter(stream, Encoding.Unicode))
{
writer.Write(xml);
}
Console.Write(xml);
using(var stream = File.OpenRead(path))
using(var reader = XmlReader.Create(stream))
{
reader.Read();
}
File.Delete(path);

how to save xmldocument to a stream

I've already written code to parse my xml file with an XmlReader so I don't want to rewrite it. I've now added encryption to the program. I have encrypt() and decrypt() functions which take an xml document and the encryption algorithm. I have a function that uses an xml reader to parse the file but now with the xml document I'm not sure how to create the xmlreader.
The question is how to save my xml document to a stream. I'm sure it's simple but I don't know anything about streams.
XmlDocument doc = new XmlDocument();
doc.PreserveWhitespace = true;
doc.Load(filep);
Decrypt(doc, key);
Stream tempStream = null;
doc.Save(tempStream); // <--- the problem is here I think
using (XmlReader reader = XmlReader.Create(tempStream))
{
while (reader.Read())
{ parsing code....... } }
You can try with MemoryStream class
XmlDocument xmlDoc = new XmlDocument( );
MemoryStream xmlStream = new MemoryStream( );
xmlDoc.Save( xmlStream );
xmlStream.Flush();//Adjust this if you want read your data
xmlStream.Position = 0;
//Define here your reading
Writing to a file:
static void Main(string[] args)
{
XmlDocument doc = new XmlDocument();
doc.LoadXml("<FTPSessionOptionInfo><HostName>ftp.badboymedia.ca</HostName></FTPSessionOptionInfo>");
using (StreamWriter fs = new StreamWriter("test.xml"))
{
fs.Write(doc.InnerXml);
}
}
I realize this is an old question, but thought it worth adding a method from this nice little blog post. This edges out some less performant methods.
private static XDocument DocumentToXDocumentReader(XmlDocument doc)
{
return XDocument.Load(new XmlNodeReader(doc));
}
try this
XmlDocument document= new XmlDocument( );
string pathTmp = "d:\somepath";
using( FileStream fs = new FileStream( pathTmp, FileMode.CreateNew ))
{
document.Save(pathTmp);
fs.Flush();
}

I want to edit my xml file

Hi I am working on XML file, here I want to give rights to user to edit my xml file nodes to his own custom language.
I am enclosing my code, but it is not editting my xml file. Need assistance.
class Program
{
static void Main(string[] args)
{
//The Path to the xml file
string path = "D://Documents and Settings//Umaid//My Documents//Visual Studio 2008//Projects//EditXML//EditXML//testing.xml";
//Create FileStream fs
System.IO.FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
//Create new XmlDocument
System.Xml.XmlDocument xmldoc = new System.Xml.XmlDocument();
//Load the contents of the filestream into the XmlDocument (xmldoc)
xmldoc.Load(fs);
//close the fs filestream
fs.Close();
//Change the contents of the attribute
xmldoc.DocumentElement.ChildNodes[0].Attributes[0].InnerText = "Umaid";
// Create the filestream for saving
FileStream WRITER = new FileStream(path, FileMode.Truncate, FileAccess.Write, FileShare.ReadWrite);
// Save the xmldocument
xmldoc.Save(WRITER);
//Close the writer filestream
WRITER.Close();
}
}
My XML file which I am going to edit, but couldn't.
<?xml version="1.0" encoding="utf-8" ?>
<rule id="city" scope="public">
<one-of>
<item>Boston</item>
</one-of>
</rule>
What do you really want to do with your XML?? Which attribute to you want to change??
One hint: you can load and save XmlDocument to a path directly - no need for the filestream .....
xmldoc.Load(#"D:\yourpath\file.xml");
xmldoc.Save(#"D:\yourpath\newfile.xml");
The problem is that your expression xmldoc.DocumentElement.ChildNodes[0] selects the <one-of> node which has no attributes.
You cannot change a non-existing attribute.
If you want to change the "id" attribute of <rule>, you need to do this on the DocumentElement:
xmldoc.DocumentElement.Attributes["id"].Value = "Umaid";
If you want to change the text inside the <item>, do this:
XmlNode itemNode = xmldoc.SelectSingleNode("/rule/one-of/item");
if(itemNode != null)
{
itemNode.InnerText = "Umaid";
}
Marc
class Program
{
static void Main(string[] args)
{
string path = "D:\\Documents and Settings\\Umaid\\My Documents\\Visual Studio 2008\\Projects\\EditXML\\EditXML\\testing.xml";
XmlDocument doc = new XmlDocument();
doc.Load(path);
var itemNode = doc.SelectSingleNode("rule/one-of/item");
if (itemNode != null)
{
itemNode.InnerText = "Umaid";
}
doc.Save(path);
}
}

Categories