Generate Xml from Xsd with ado.net - c#

I want to generate xml from a xsd, this xml I want to contain specify attributes from xsd. Any ideas?
string fn = System.IO.Path.GetFileName(File1.PostedFile.FileName);
string SaveLocation = Server.MapPath("Data") + "\\" + fn;
try
{
File1.PostedFile.SaveAs(SaveLocation);
Response.Write("The file has been uploaded.");
}
catch (Exception ex)
{
Response.Write("Error: " + ex.Message);
//Note: Exception.Message returns a detailed message that describes the current exception.
//For security reasons, we do not recommend that you return Exception.Message to end users in
//production environments. It would be better to put a generic error message.
}
try
{
XmlTextReader reader = new XmlTextReader(SaveLocation);
//XmlSchema myschema = XmlSchema.Read(reader, ValidationCallback);
while (reader.Read())
{
// LiteralURL.Text += reader.ReadString();
}
// Response.Write("\t"+myschema.Items);
XDocument doc = XDocument.Load(SaveLocation);
var ListNode = new List<XNode>();
if (doc != null)
{
Response.Write("nu este null");
}
else
{
Response.Write("Null !");
}
int i = 0;
string str = "";
foreach (XNode nodes in doc.Elements())
{
str = "node1: " + nodes.ToString();
ListNode[i] = nodes;
i++;
}
for(int j = 0; j < i; i++)
{
Response.Write("FirstNode:"+ ListNode[j]);
}
//Response.Write("FirstNode:" );
Response.Write(str);
}
catch (Exception ex)
{
}
}
else
{
Response.Write("Please select a file to upload.");
}

Have a look at xsd.exe. You run this against your XSD and it gives you classes based on the XSD elements and attributes. You don't need to work with raw XML or XSD after that.

Related

How to write and update a user score that is stored in a textfile in c#?

I am making a quiz game for my A level computing coursework. The quiz works fine, but the problem is that at the end of the quiz I want to save the users score and username to a text file. I have already tried to search for the answer both on Stack Overflow and other websites, but I couldn't find an answer.
At the end of the quiz I have a form called EndForm and when that form loads, I call a method called SaveScore(). The code is down below. I want this method to save the username and score of the user in the scores.txt file. I also want the users score to be updated if the user replays the quiz and gets a higher score. I don't know why my current code is not working.
private void SaveScore()
{
string file = #"..\..\textfiles\scores.txt";
FileStream fileStream;
StreamWriter streamWriter;
try
{
if (File.Exists(file))
{
string[] HighScore = File.ReadAllLines(file).ToArray();
string[] contents = new string[] { };
File.WriteAllLines(file, contents);
fileStream = new FileStream(file, FileMode.Create, FileAccess.Write);
streamWriter = new StreamWriter(fileStream);
for (int i = 0; i < HighScore.Length; i++)
{
string[] HighScores = HighScore[i].Split('~');
string username = HighScores[0];
int currentScore = Convert.ToInt32(HighScores[1]);
if (player.Score > currentScore)
{
streamWriter.WriteLine(player.Name + "~" + player.Score);
for (int x = i; x < 4; x++)
{
string[] newHighScore = HighScore[x].Split('~');
string newUsername = newHighScore[0];
int newScore = Convert.ToInt32(newHighScore[1]);
streamWriter.WriteLine(newUsername + "~" + newScore);
}
break;
}
else
{
streamWriter.WriteLine(username + "~" + currentScore);
}
streamWriter.Close();
fileStream.Close();
//Write player score data to file if it is not already there.
if (HighScore.Length < 10)
{
fileStream = new FileStream(file, FileMode.Append, FileAccess.Write);
streamWriter = new StreamWriter(fileStream);
streamWriter.WriteLine(player.Name + "~" + player.Score);
streamWriter.Close();
fileStream.Close();
}
}
}
}
catch
{
MessageBox.Show("Error saving high score", "Error");
}
}
Any help would be appreciated, thanks in advance.
This should do everything you need - if you have any questions just ask. May I also suggest using a CSV rather than a text file? Simply change the extension.
private void SaveScore()
{
String scoresFilePath = #"..\..\textfiles\scores.txt";
try
{
//
// Create file if not exists
//
if (!File.Exists(scoresFilePath))
{
File.Create(scoresFilePath).Dispose();
}
//
// Create DataTable
//
DataColumn nameColumn = new DataColumn("name", typeof(String));
DataColumn scoreColumn = new DataColumn("score", typeof(int));
DataTable scores = new DataTable();
scores.Columns.Add(nameColumn);
scores.Columns.Add(scoreColumn);
//
// Read CSV and populate DataTable
//
using (StreamReader streamReader = new StreamReader(scoresFilePath))
{
streamReader.ReadLine();
while (!streamReader.EndOfStream)
{
String[] row = streamReader.ReadLine().Split(',');
scores.Rows.Add(row);
}
}
Boolean scoreFound = false;
//
// If user exists and new score is higher, update
//
foreach (DataRow score in scores.Rows)
{
if ((String)score["name"] == player.Name)
{
if ((int)score["score"] < player.Score)
{
score["score"] = player.Score;
}
scoreFound = true;
break;
}
}
//
// If user doesn't exist then add user/score
//
if (!scoreFound)
{
scores.Rows.Add(player.Name, player.Score);
}
//
// Write changes to CSV (empty then rewrite)
//
File.WriteAllText(scoresFilePath, string.Empty);
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.AppendLine("name,score");
foreach (DataRow score in scores.Rows)
{
stringBuilder.AppendLine(score["name"] + "," + score["score"]);
}
File.WriteAllText(scoresFilePath, stringBuilder.ToString());
}
catch(Exception ex)
{
MessageBox.Show("Error saving high score:\n\n" + ex.ToString(), "Error");
}
}
Try not to swallow the exception and you should get a useful error message. Change:
catch
{
MessageBox.Show("Error saving high score", "Error");
}
to
catch(Exception ex)
{
MessageBox.Show("Error saving high score: " + ex.ToString(), "Error");
}

How to loop XmlTextReader properly (C#)?

Below is a sample of the type of XML file I am trying to handle. If I have only one part along with an accompanying number/character I can process the data extraction without the necessity of the 'if (!reader.EOF)' control structure. However when I try to include this structure so that I can loop back to checking for another part, number, and character group, it deadlocks.
Any advice as to how to do this properly? This was the most efficient idea that popped into my head. I am new to reading data from XMLs.
Sample Xml:
<?xml version="1.0" encoding="UTF-8"?>
<note>
<part>100B</part>
<number>45</number>
<character>a</character>
<part>100C</part>
<number>55</number>
<character>b</character>
</note>
Code:
String part = "part";
String number = "number";
String character = "character";
String appendString = "";
StringBuilder sb = new StringBuilder();
try
{
XmlTextReader reader = new XmlTextReader("myPath");
while (reader.Read())
{
switch (reader.NodeType)
{
case XmlNodeType.Element: // The node is an element.
myLabel:
if (reader.Name == part)
{
part = reader.ReadInnerXml();
}
if (reader.Name == number)
{
number = reader.ReadInnerXml();
number = double.Parse(number).ToString("F2"); //format num
}
if (reader.Name == character)
{
character = reader.ReadInnerXml();
}
//new string
appendString = ("Part: " + part + "\nNumber: " + number +
"\nCharacter: " + character + "\n");
//concatenate
sb.AppendLine(appendString);
if (reader.EOF != true)
{
Debug.Log("!eof");
part = "part";
number = "number";
character = "character";
goto myLabel;
}
//print fully concatenated result
sb.ToString();
//reset string builder
sb.Length = 0;
break;
}
}
}
catch (XmlException e)
{
// Write error.
Debug.Log(e.Message);
}
catch (FileNotFoundException e)
{
// Write error.
Debug.Log(e);
}
catch(ArgumentException e)
{
// Write error.
Debug.Log(e);
}
XmlReader class has many useful methods. Use it.
See this:
var sb = new StringBuilder();
using (var reader = XmlReader.Create("test.xml"))
{
while (reader.ReadToFollowing("part"))
{
var part = reader.ReadElementContentAsString();
sb.Append("Part: ").AppendLine(part);
reader.ReadToFollowing("number");
var number = reader.ReadElementContentAsDouble();
sb.Append("Number: ").Append(number).AppendLine();
reader.ReadToFollowing("character");
var character = reader.ReadElementContentAsString();
sb.Append("Character: ").AppendLine(character);
}
}
Console.WriteLine(sb);
Alexander's answer is fine, I just want to add sample using XDocument, according comments of Jon Skeet:
var sb = new StringBuilder();
var note = XDocument.Load("test.xml").Root.Descendants();
foreach (var el in note)
{
sb.Append(el.Name).Append(": ").AppendLine(el.Value);
}
Console.WriteLine(sb);

XmlException Invalid character in the given encoding

Hello I searched the internet this exception,
I have not found solution so I decided to ask.
in a console application I need to search a folder a certain number of xml files. such file is encoded in ANSI.
  what the application does is to take the file and convert it to utf-8 encoding.
but as the cycle goes catch this exception.
Invalid character in the given encoding. Line 1, position 2757
I get the xml from a third
alguna Idea? muchas gracias.
this is my code
i get this exception in 3 xmls of 100
int Count = 0;
string sNombre = "";
string targetPath = #"C:\SomePath\";
string logError = "log_xml_Error.log";
if (File.Exists(#"log_xml_Error.log"))
{
File.Delete(#"log_xml_Error.log");
}
Console.WriteLine("press enter");
Console.ReadLine();
string[] xmls = Directory.GetFiles(targetPath, "*.xml", SearchOption.AllDirectories);
foreach (var sFile in xmls)
{
try
{
Count++;
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(sFile);
byte[] sXmlByte = Encoding.UTF8.GetBytes(xmlDoc.OuterXml);
sName = Path.GetFileName(sFile);
string sCompletePathXML = #"C:\SomePath\" + sName;
if (!File.Exists(sCompletePathXML))
{
File.WriteAllText(sCompletePathXML, System.Text.UTF8Encoding.UTF8.GetString(sXmlByte), System.Text.UTF8Encoding.UTF8);
}
Console.WriteLine(Count);
}
catch (Exception ex)
{
using (StreamWriter sw = File.AppendText(logError))
{
sw.WriteLine(" Error: " + ex.Message + "XML :" + sName);
}
}
}
Console.WriteLine("process complete");
Console.ReadLine();
what the application does is to take the file and convert it to utf-8 encoding
I would simle do
var xdoc = XDocument.Parse(File.ReadAllText(filename,Encoding.ASCII));
File.WriteAllText(filename, xdoc.ToString(), Encoding.UTF8);

Reading specific text from XML files

I have created a small XML tool which gives me count of specific XML tags from multiple XML files.
The code for this is as follow:
public void SearchMultipleTags()
{
if (txtSearchTag.Text != "")
{
try
{
//string str = null;
//XmlNodeList nodelist;
string folderPath = textBox2.Text;
DirectoryInfo di = new DirectoryInfo(folderPath);
FileInfo[] rgFiles = di.GetFiles("*.xml");
foreach (FileInfo fi in rgFiles)
{
int i = 0;
XmlDocument xmldoc = new XmlDocument();
xmldoc.Load(fi.FullName);
//rtbox2.Text = fi.FullName.ToString();
foreach (XmlNode node in xmldoc.GetElementsByTagName(txtSearchTag.Text))
{
i = i + 1;
//
}
if (i > 0)
{
rtbox2.Text += DateTime.Now + "\n" + fi.FullName + " \nInstance: " + i.ToString() + "\n\n";
}
else
{
//MessageBox.Show("No Markup Found.");
}
//rtbox2.Text += fi.FullName + "instances: " + str.ToString();
}
}
catch (Exception)
{
MessageBox.Show("Invalid Path or Empty File name field.");
}
}
else
{
MessageBox.Show("Dont leave field blanks.");
}
}
This code returns me the tag counts in Multiple XML files which user wants.
Now the same I want to Search for particular text and its count present in XML files.
Can you suggest the code using XML classes.
Thanks and Regards,
Mayur Alaspure
Use LINQ2XML instead..It's simple and a complete replacement to othe XML API's
XElement doc = XElement.Load(fi.FullName);
//count of specific XML tags
int XmlTagCount=doc.Descendants().Elements(txtSearchTag.Text).Count();
//count particular text
int particularTextCount=doc.Descendants().Elements().Where(x=>x.Value=="text2search").Count();
System.Xml.XPath.
Xpath supports counting: count(//nodeName)
If you want to count nodes with specific text, try count(//*[text()='Hello'])
See How to get count number of SelectedNode with XPath in C#?
By the way, your function should probably look something more like this:
private int SearchMultipleTags(string searchTerm, string folderPath) { ...
//...
return i;
}
Try using XPath:
//var document = new XmlDocument();
int count = 0;
var nodes = document.SelectNodes(String.Format(#"//*[text()='{0}']", searchTxt));
if (nodes != null)
count = nodes.Count;

Xml bulk Nodes appending issue

I want to generate a million record xml file.For this i have a sample xml file with only one value set.Using this xml file fill ramdom values a million times.
I created a solutin but it is very time consuming one.My code is
try
{
label1.Text = "File creation in progress ...";
Random rnd = new Random();
string sStartupPath = Application.StartupPath;
string sName = "";
int flag = 0;
XmlDocument XmlFile = new XmlDocument();
XmlFile.Load(sStartupPath + #"..\..\..\BankStatement.xml");
XmlFile.Save(#"C:\XmlData\Bank.xml");
XmlDocument XmlF = new XmlDocument();
XmlF.Load(#"C:\XmlData\Bank.xml");
long k = Convert.ToInt32(textBox1.Text);
for (int j = 1; j < k; j++)
{
XmlTextReader objXmlTextReader = new XmlTextReader(sStartupPath + #"..\..\..\BankStatement.xml");
while (objXmlTextReader.Read())
{
switch (objXmlTextReader.NodeType)
{
case XmlNodeType.Element:
sName = objXmlTextReader.Name;
if (sName == "DataXml")
{
if (flag == 0)
flag = 1;
}
break;
case XmlNodeType.Text:
if (flag == 1)
{
XmlNodeList elemList = XmlFile.GetElementsByTagName(sName);
for (int i = 0; i < elemList.Count; i++)
{
if (elemList[i].Name == "Name")
elemList[i].InnerXml = generateNames();
else if (elemList[i].Name == "EmailID")
elemList[i].InnerXml = generatemailids();
else
elemList[i].InnerXml = rnd.Next(500000).ToString();
}
}
break;
case XmlNodeType.EndElement:
sName = objXmlTextReader.Name;
if (sName == "DataXml")
{
if (flag == 1)
flag = 0;
}
break;
}
}
XmlDocument dd = new XmlDocument();
dd.LoadXml(XmlFile.InnerXml);
XmlNodeList node=dd.GetElementsByTagName("Customers");
XmlDocumentFragment xfrag = XmlF.CreateDocumentFragment();
xfrag.RemoveAll();
for (int i = 0; i < 1; i++)
{
xfrag.InnerXml = node[i].InnerXml;
XmlF.DocumentElement.FirstChild.AppendChild(xfrag);
}
XmlF.Save(#"C:\XmlData\Bank.xml");
}
label1.Visible = false;
MessageBox.Show("File creation success..!");
}
catch (Exception ex)
{
label1.Text = "";
MessageBox.Show("Error Occured");
}
Please give me a better solution.
The fastest method I know to write XML (short of building the XML fragments manually) is to use XmlWriter
The XmlWriter class is an abstract base class that provides a
forward-only, write-only, non-cached way of generating XML streams. It
can be used to build XML documents that conform to the W3C Extensible
Markup Language (XML) 1.0 (fourth edition) recommendation and the
Namespaces in XML recommendation.
MSDN has a walkthrough on how to use the abstract XmlWriter class.
For writing large XML files you should use XmlTextWriter.

Categories