I've the below c# code and i'm getting the current index is out of range error
public partial class FrmTreeViewContinents : Form
{
// Objets communs
XmlDocument monXml = new XmlDocument();
XmlNodeList listeNode = null;
XmlNode root = null;
public FrmTreeViewContinents()
{
InitializeComponent();
}
private void btnTransferToXml_Click(object sender, EventArgs e)
{
ManipXml obj = new ManipXml();
// Sérialise une collection d'objets 'Pays' en fichier XML
obj.SerialiseObjets("Pays.xml");
}
private void btnAfficheEntity_Click(object sender, EventArgs e)
{
// Chargement du fichier XML - Abandon si erreur
if (!ChargeFichierXml()) return;
// Sélecton des données dans le noeud XML 'Pays'
listeNode = root.SelectNodes("//Pays");
// Affichage des données lues
AffichageDonnees();
}
// Méthode d'affichage des données lues dans le fichier XML
private void AffichageDonnees()
{
txtBoxAffiche.Clear();
foreach (XmlNode noeud in listeNode)
{
txtBoxAffiche.Text += noeud.Attributes[2].InnerText.ToString() +
" - " +
noeud.Attributes[3].InnerText.ToString() +
" - " +
noeud.Attributes[4].InnerText.ToString() +
Environment.NewLine;
}
}
// Méthode de chargement du fichier XML
private bool ChargeFichierXml()
{
try
{
monXml.Load("Pays.xml");
}
catch (Exception ex)
{
MessageBox.Show("Erreur sur chargement du fichier XML"
+ Environment.NewLine + ex.Message,
"Erreur",
MessageBoxButtons.OK,
MessageBoxIcon.Error);
return false;
}
//XmlNodeList listeNode;
root = monXml.DocumentElement;
return true;
}
}
class ManipXml
{
// Cette méthode permet de générer un fichier XML avec une collection de 'Pays'
public void SerialiseObjets(string sNomFichierXml)
{
XmlSerializer xmlSerializer = new XmlSerializer(typeof(Collection<Pays>));
Collection<Pays> colPays = new Collection<Pays>();
Pays cnt1 = new Pays();
cnt1.NomPays = "Australie";
cnt1.NomCapitalePays = "Canberra";
cnt1.NomContinent = "Australie";
Pays cnt2 = new Pays();
cnt2.NomPays = "France";
cnt2.NomCapitalePays = "Paris";
cnt2.NomContinent = "Europe";
Pays cnt3 = new Pays();
cnt3.NomPays = "Espagne";
cnt3.NomCapitalePays = "Madrid";
cnt3.NomContinent = "Europe";
Pays cnt4 = new Pays();
cnt4.NomPays = "Chine";
cnt4.NomCapitalePays = "Beijing";
cnt4.NomContinent = "Asie";
Pays cnt5 = new Pays();
cnt5.NomPays = "Malaysia";
cnt5.NomCapitalePays = "Kuala-Lumpur";
cnt5.NomContinent = "Asie";
// Ajout des 'Continent' dans la collection
colPays.Add(cnt1);
colPays.Add(cnt2);
colPays.Add(cnt3);
colPays.Add(cnt4);
colPays.Add(cnt5);
// Instanciation d'un Stream
Stream st = new FileStream(sNomFichierXml, FileMode.Create);
// Génération du fichier XML
xmlSerializer.Serialize(st, colPays);
st.Close();
}
}
public class Pays // Définition de la classe Continent
{
public string NomPays { get; set; }
public string NomCapitalePays { get; set; }
public string NomContinent { get; set; }
}
the error i got is in the section below , which is "the current index is out of range"
foreach (XmlNode noeud in listeNode){
txtBoxAffiche.Text += noeud.Attributes[2].InnerText.ToString() +" - "
+ noeud.Attributes[3].InnerText.ToString() + " - "
+ noeud.Attributes[4].InnerText.ToString() +
Environment.NewLine;
}
can you please help me
thank you
Problem : You might be accessing the invalid Attributes of the Pays.xml file.
Solution: You need to check the Attributes.Count property before accessing the Attributes of the Pays.xml file.
Try This:
foreach (XmlNode noeud in listeNode)
{
for(int i=2;i<noeud.Attributes.Count;i++)
{
if(i!=noeud.Attributes.Count-1)
txtBoxAffiche.Text += noeud.Attributes[i].InnerText.ToString() +" - ";
else
txtBoxAffiche.Text += noeud.Attributes[i].InnerText.ToString() + Environment.NewLine;
}
}
The error is due to you are using the Index out of range.
for example if Array size 3 but if you try to access 4th index ,it will give error.
so please check this part for index value
foreach (XmlNode noeud in listeNode){
txtBoxAffiche.Text += noeud.Attributes[2].InnerText.ToString() +" - "
+ noeud.Attributes[3].InnerText.ToString() + " - "
+ noeud.Attributes[4].InnerText.ToString() +
Environment.NewLine;
}
The problem is in one of the Attributes[] index. You get the position 2, 3 and 4, and I bet that you don't have that many Attributes (4, 3 or 2).
You can set that values first to some variables before using them.
string attribute2 = noeud.Attributes[2].InnerText.ToString();
string attribute3 = noeud.Attributes[3].InnerText.ToString();
string attribute4 = noeud.Attributes[4].InnerText.ToString();
But this isn't a very good practice.... You would check first if the attribute exists.
string attribute2;
if (noeud.Attributes[2] != null) {
attribute2 = noeud.Attributes[2].InnerText.ToString();
}
Related
I recently develloped a C# app which goes through directories and subdirectories and apply my if/else instruction on 13 type of .csv files and push informations into my SQL Server Database .
I created a table with Directories and files count , and also the datetime of the treatement , and i want to fill it with these informations , so i could do some comparison and see if there is any missing/error , and have a kind of logs about how much data I entered on my db every day . Is there a way to do it with GetFiles/GetDirectories property ? Or with a SQLBulkCopy ? Or any other kind of C# code ? i searched a lot and could'nt find any proper solution .
Thanks for your listening .
Here is my code :
bool _CompareFileName(string fileName, string id)
{
if (fileName.Substring(fileName.Length - id.Length, id.Length) == id) // On compare les fichiers par rapport à leur " id "
return true;
else
return false;
}
public void LogFile(string sExceptionName, string sEventName, string sControlName, int nErrorLineNo, string sFormName)
{
StreamWriter log;
if (!File.Exists("logfile.txt"))
{
log = new StreamWriter("logfile.txt");
}
else
{
log = File.AppendText("logfile.txt");
}
// Write to the file:
log.WriteLine("Data Time:" + DateTime.Now);
log.WriteLine("Exception Name:" + sExceptionName);
log.WriteLine("Event Name:" + sEventName);
log.WriteLine("Control Name:" + sControlName);
log.WriteLine("Error Line No.:" + nErrorLineNo);
log.WriteLine("Form Name:" + sFormName);
// Close the stream:
log.Close();
}
public void CsvToSql(string strCmdText) // La méthode permettant d'entrer les données du CSV à la table SQL
{
try
{
DirectoryInfo dir = new DirectoryInfo("U:/FichiersINPI/IMR_Donnees_Saisies/tc/flux/2017/06/01/");
Console.WriteLine("Recherche de fichier .csv convertis :"); //Fonction de recherche des csv convertis précédemment
//On utilise un StreamWriter pour écrire les sorties de boucle dans un .bat
using (StreamWriter writer = new StreamWriter("U:/FichiersINPI/IMR_Donnees_Saisies/tc/flux/2017/06/01/CsvSql.bat"))
foreach (var Fi in Directory.GetFiles("U:/FichiersINPI/IMR_Donnees_Saisies/tc/flux/2017/06/01/", "*.csv", SearchOption.AllDirectories)) //On précise qu'on veut tout les répértoires
{
if (_CompareFileName(Fi, "1_PM.csv")) // Boucle If pour les 13 types de fichiers
{
writer.WriteLine("Csv2Sql_new " + Fi + " IMR_INPI..PM /force"); //Personne Morale
}
else if (_CompareFileName(Fi, "2_PM_EVT.csv"))
{
writer.WriteLine("Csv2Sql_new " + Fi + " IMR_INPI..PM_EVT /force"); //Evenement Personne Morale
}
else if (_CompareFileName(Fi, "3_PP.csv"))
{
writer.WriteLine("Csv2Sql_new " + Fi + " IMR_INPI..PP /force"); // Personne Physique
}
else if (_CompareFileName(Fi, "4_PP_EVT.csv"))
{
writer.WriteLine("Csv2Sql_new " + Fi + " IMR_INPI..PP_EVT /force"); //Evenement Personne Physique
}
else if (_CompareFileName(Fi, "5_rep.csv"))
{
writer.WriteLine("Csv2Sql_new " + Fi + " IMR_INPI..Rep /force"); // Représentants
}
else if (_CompareFileName(Fi, "6_rep_nouveau_modifie_EVT.csv"))
{
writer.WriteLine("Csv2Sql_new " + Fi + " IMR_INPI..Rep_new /force"); // Modification relative aux représentants
}
else if (_CompareFileName(Fi, "7_rep_partant_EVT.csv"))
{
writer.WriteLine("Csv2Sql_new " + Fi + " IMR_INPI..Rep_supression /force"); // Supression d'un représentant
}
else if (_CompareFileName(Fi, "8_ets.csv"))
{
writer.WriteLine("Csv2Sql_new " + Fi + " IMR_INPI..Ets /force"); // Etablissements
}
else if (_CompareFileName(Fi, "9_ets_nouveau_modifie_EVT.csv"))
{
writer.WriteLine("Csv2Sql_new " + Fi + " IMR_INPI..Ets_modification /force"); // Modification relative aux établissements
}
else if (_CompareFileName(Fi, "10_ets_supprime_EVT.csv"))
{
writer.WriteLine("Csv2Sql_new " + Fi + " IMR_INPI..Ets_supression /force"); // Supression d'un établissement
}
else if (_CompareFileName(Fi, "11_obs.csv"))
{
writer.WriteLine("Csv2Sql_new " + Fi + " IMR_INPI..Obs /force"); // Observation
}
else if (_CompareFileName(Fi, "12_actes.csv"))
{
writer.WriteLine("Csv2Sql_new " + Fi + " IMR_INPI..Acte /force"); // Actes
}
else if (_CompareFileName(Fi, "13_comptes_annuels.csv"))
{
writer.WriteLine("Csv2Sql_new " + Fi + " IMR_INPI..Compte_annuel /force"); //Comptes annuels
}
else // On conclue la boucle par un catch qui arrête le traitement automatique en cas d'erreur ( Table pas assez large , fichier corrompu .. )
{
}
}
//On execute le .bat
Process.Start("CMD.exe", "/C start U:/FichiersINPI/IMR_Donnees_Saisies/tc/flux/2017/06/01/CsvSql.bat");
Console.WriteLine("Fichier bat executé avec succés , données intégrées");
}
catch (Exception ex)
{
Console.WriteLine("Il y a un eu une erreur : " + ex.ToString());
}
}
A checked radiobutton doesn`t appear checked on the windows form.
I have tested it with a messagebox and it written has checked...
You can ask for more code/information.
The language is french.
Thanks for help
New picture: The console output is correct according to my sql database.
// LOAD RADIOBUTTON
SQLCommand.CommandText = ChargementRadiobuttonCommandText;
reader = SQLCommand.ExecuteReader();
// Rempli une liste avec les réponses provenant de la base de donné
while (reader.Read())
{
ReponsesRadioButton.Add(reader["ReponseRadioButton"].ToString());
}
//foreach (string current in ReponsesRadioButton)
//{
// MessageBox.Show(current);
//}
//MessageBox.Show("0: " + ReponsesRadioButton[0]);
//MessageBox.Show("11 " + ReponsesRadioButton[11]);
//MessageBox.Show("cathegorie: " + SessionQuestionGeneral.getintCathegorieActuel().ToString());
//nombreDeQuestions = 0;
//switch (SessionQuestionGeneral.getintCathegorieActuel())
//{
// case 1:
// nombreDeQuestions = 12;
// break;
// case 2:
// nombreDeQuestions = 7;
// break;
// case 3:
// nombreDeQuestions = 7;
// break;
// case 4:
// nombreDeQuestions = 3;
// break;
//}
//for (int questionDeLaFenetre = 0; questionDeLaFenetre < nombreDeQuestions; questionDeLaFenetre++)
//{
foreach (string ReponseRadioButton in ReponsesRadioButton)
{
//
switch (ReponseRadioButton)
{
case "En accord":
listRadioButtonEnAccord[iterationQuestion].Checked = true;
break;
case "En desaccord":
listRadioButtonEndesaccord[iterationQuestion].Checked = true;
break;
case "Non applicable":
listRadioButtonNonapplicable[iterationQuestion].Checked = true;
break;
}
//MessageBox.Show(iterationQuestion.ToString() + " " + ReponseRadioButton);
iterationQuestion++;
}
//MessageBox.Show("listRadioButtonEnAccord10 " + listRadioButtonEnAccord[10].Checked.ToString());
//MessageBox.Show("listRadioButtonEndesaccord10 " + listRadioButtonEndesaccord[10].Checked.ToString());
//MessageBox.Show("listRadioButtonNonapplicable10 " + listRadioButtonNonapplicable[10].Checked.ToString());
//MessageBox.Show("listRadioButtonEnAccord11 " + listRadioButtonEnAccord[11].Checked.ToString());
//MessageBox.Show("listRadioButtonEndesaccord11 " + listRadioButtonEndesaccord[11].Checked.ToString());
//MessageBox.Show("listRadioButtonNonapplicable11 " + listRadioButtonNonapplicable[11].Checked.ToString());
reader.Close();
ReponsesRadioButton.Clear();
iterationQuestion = 0;
// LOAD LABEL cathegorie
SQLCommand.CommandText = cathegorieCommandText;
reader = SQLCommand.ExecuteReader();
while (reader.Read())
{
cathegorieText.Text = reader["nomCathegoriequestiongenerale"].ToString();
}
reader.Close();
Did you tried the code below?
this.Update();
or
this.Refresh();
Do this to update your form, in some method in Form class.
I fixed my problem with this: reponseGroupBox[iterationQuestion].Controls.OfType<RadioButton>()
seem to be more effective.
foreach (string ReponseRadioButton in ReponsesRadioButton)
{
foreach (RadioButton radioButtonActuel in reponseGroupBox[iterationQuestion].Controls.OfType<RadioButton>()) // Pour chaque RadioButton du reponseGroupBox associé à questionActuel
{
if (radioButtonActuel.Text == "En accord" && ReponseRadioButton == "En accord")
{
radioButtonActuel.Checked = true;
}
if (radioButtonActuel.Text == "En desaccord" && ReponseRadioButton == "En desaccord")
{
radioButtonActuel.Checked = true;
}
if (radioButtonActuel.Text == "Non applicable" && ReponseRadioButton == "Non applicable")
{
radioButtonActuel.Checked = true;
}
}
iterationQuestion++;
}
I would like my web browser to save visited sights into a history xml file.I have two forms for history and web browser. I would like to get the url bar text into my history form where I have the method to to write an xml file.
This is what I tried. (web browser form)
public String historyURL
{
get
{
return urlBar.Text;
}
And in my History form I tried to call this method
private void addHistory(string url, string data)
{
url = this.WebBrowserForm.historyURL.ToString();
XmlDocument myXml = new XmlDocument();
int i=1;
XmlElement el = myXml.CreateElement("item");
el.SetAttribute("url", url);
el.SetAttribute("lastVisited", data);
My showHistory method
private void showHistory()
{
historyTreeView.Nodes.Clear();
XmlDocument myXml = new XmlDocument();
if (File.Exists(historyXml))
{
myXml.Load(historyXml);
DateTime now = DateTime.Now;
if (sortHistory.Text.Equals("Ordered Visited Today"))
{
historyTreeView.ShowRootLines = false;
foreach (XmlElement el in myXml.DocumentElement.ChildNodes)
{
DateTime d = DateTime.Parse(el.GetAttribute("lastVisited"));
if (!(d.Date == now.Date)) return;
TreeNode node =
new TreeNode(el.GetAttribute("url"), 3, 3);
node.ToolTipText = el.GetAttribute("url") + "\nLast Visited: " + el.GetAttribute("lastVisited") + "\nTimes Visited: " + el.GetAttribute("times");
node.Name = el.GetAttribute("url");
node.ContextMenuStrip = histContextMenu;
historyTreeView.Nodes.Add(node);
}
}
if (sortHistory.Text.Equals("View by Date"))
{
historyTreeView.ShowRootLines = true;
historyTreeView.Nodes.Add("2 Weeks Ago", "2 Weeks Ago", 2, 2);
historyTreeView.Nodes.Add("Last Week", "Last Week", 2, 2);
historyTreeView.Nodes.Add("This Week", "This Week", 2, 2);
historyTreeView.Nodes.Add("Yesterday", "Yesterday", 2, 2);
historyTreeView.Nodes.Add("Today", "Today", 2, 2);
foreach (XmlElement el in myXml.DocumentElement.ChildNodes)
{
DateTime d = DateTime.Parse(el.GetAttribute("lastVisited"));
TreeNode node = new TreeNode(el.GetAttribute("url"), 3, 3);
node.ToolTipText = el.GetAttribute("url") + "\nLast Visited: " + el.GetAttribute("lastVisited") + "\nTimes Visited: " + el.GetAttribute("times");
node.Name = el.GetAttribute("url");
node.ContextMenuStrip = histContextMenu;
if (d.Date == now.Date)
historyTreeView.Nodes[4].Nodes.Add(node);
else
if (d.AddDays(1).ToShortDateString().Equals(now.ToShortDateString()))
historyTreeView.Nodes[3].Nodes.Add(node);
else
if (d.AddDays(7) > now)
historyTreeView.Nodes[2].Nodes.Add(node);
else
if (d.AddDays(14) > now)
historyTreeView.Nodes[1].Nodes.Add(node);
else
if (d.AddDays(21) > now)
historyTreeView.Nodes[0].Nodes.Add(node);
else
if (d.AddDays(22) > now)
myXml.DocumentElement.RemoveChild(el);
}
My full addHistory method for refference
private void addHistory(string url, string data)
{
url = this.WebBrowserForm.historyURL.ToString();
XmlDocument myXml = new XmlDocument();
int i=1;
XmlElement el = myXml.CreateElement("item");
el.SetAttribute("url", url);
el.SetAttribute("lastVisited", data);
if (!File.Exists(historyXml))
{
XmlElement root = myXml.CreateElement("history");
myXml.AppendChild(root);
el.SetAttribute("times", "1");
root.AppendChild(el);
}
else
{
myXml.Load(historyXml);
foreach (XmlElement x in myXml.DocumentElement.ChildNodes)
{
if (x.GetAttribute("url").Equals(url))
{
i = int.Parse(x.GetAttribute("times")) + 1;
myXml.DocumentElement.RemoveChild(x);
break;
}
}
el.SetAttribute("times", i.ToString());
myXml.DocumentElement.InsertBefore(el, myXml.DocumentElement.FirstChild);
/*ordered visited today*/
if (sortHistory.Text.Equals("Ordered Visited Today"))
{
if (!historyTreeView.Nodes.ContainsKey(url))
{
TreeNode node =
new TreeNode(url, 3, 3);
node.ToolTipText = url + "\nLast Visited: " + data + "\nTimes visited :" + i.ToString();
node.Name = url.ToString();
node.ContextMenuStrip = histContextMenu;
historyTreeView.Nodes.Insert(0, node);
}
else
historyTreeView.Nodes[url].ToolTipText
= url + "\nLast Visited: " + data + "\nTimes visited: " + i.ToString();
}
/* view by date*/
if (sortHistory.Text.Equals("View by Date"))
{
if (historyTreeView.Nodes[4].Nodes.ContainsKey(url))
historyTreeView.Nodes[url].ToolTipText
= url.ToString() + "\nLast Visited: " + data + "\nTimes visited: " + i.ToString();
else
{
TreeNode node =
new TreeNode(url, 3, 3);
node.ToolTipText = url + "\nLast Visited: " + data + "\nTimes visited :" + i.ToString();
node.Name = url;
node.ContextMenuStrip = histContextMenu;
historyTreeView.Nodes[4].Nodes.Add(node);
}
}
}
myXml.Save(historyXml);
}
Where am I going wrong?
I want to append this Line to the source code which will be compiled :
Temp.AppendLine(#"[assembly: AssemblyDescription("[DESCRIPTION]"]);");
But you see the [DESCRIPTION] is not in the string too...
Instead of the [DISCRIPTION] I want to use the input of an TextBox. How can I do that?
private void button1_Click(object sender, EventArgs e)
{
SaveFileDialog d = new SaveFileDialog();
d.Filter = "Executable (*.exe)|*.exe";
if (d.ShowDialog() == DialogResult.OK)
{
String InputCode = String.Empty;
String regcode = String.Empty;
//Unser TestCode, in dem Wir ein MessageBox aufrufen
InputCode = "MessageBox.Show((1 + 2 + 3).ToString());";
System.CodeDom.Compiler.CodeDomProvider CodeDomProvider = System.CodeDom.Compiler.CodeDomProvider.CreateProvider("CSharp");
//Parameter für die Compilierung, wie die einzubindenen Bibliotheken usw.
System.CodeDom.Compiler.CompilerParameters CompilerParameters = new System.CodeDom.Compiler.CompilerParameters();
CompilerParameters.ReferencedAssemblies.Add("System.dll");
CompilerParameters.OutputAssembly = d.FileName;
CompilerParameters.ReferencedAssemblies.Add("System.Windows.Forms.dll");
CompilerParameters.CompilerOptions += "/target:winexe" + " " + "/win32icon:" + "\"" + textBox6.Text + "\"";
CompilerParameters.GenerateExecutable = true;
CompilerParameters.GenerateInMemory = false;
//Über den StringBuilder wird der Code zusammengesetzt
StringBuilder Temp = new StringBuilder();
Temp.AppendLine(#"using System;");
Temp.AppendLine(#"using System.Windows.Forms;");
Temp.AppendLine(#"using System.Diagnostics;");
Temp.AppendLine(#"namespace RunTimeCompiler{");
Temp.AppendLine(#"public class Test{");
Temp.AppendLine(#"public static void Main(){");
Temp.AppendLine(#InputCode);
Temp.AppendLine(#"}");
Temp.AppendLine(#"public void Ergebnis(){");
Temp.AppendLine(#"}}}");
//Compilieren
System.CodeDom.Compiler.CompilerResults CompilerResults = CodeDomProvider.CompileAssemblyFromSource(CompilerParameters, Temp.ToString());
//Auf CompilerFehler prüfen
if (CompilerResults.Errors.Count > 0)
{
MessageBox.Show(CompilerResults.Errors[0].ErrorText, "Fehler bei Laufzeitkompilierung", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
else
{
MessageBox.Show("Done", "Finished", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
Take the TextBox input, convert it to a C# string literal and place it within the string that contains the attribute code:
string description = textBox1.Text;
string descriptionAsCsharpStringLiteral =
"#\"" + description.Replace("\"", "\"\"") + "\"";
string attribute =
"[assembly: AssemblyDescription(" + descriptionAsCsharpStringLiteral + ")]";
Temp.AppendLine("using System.Reflection;")
.AppendLine(attribute)
.AppendLine("namespace ...");
I can get the version date and version number to show up, but for the remaining information I want it to output the element name followed by the information within the tag. In the end I'd like it to read something like:
versionDate: 2011-10-04
versionNumber: 1.0
FirstName: Bob
LastName: Johnson
PhoneNumber: 123-456-7890
FaxNumber: 111-111-1111
EmailAddress: bjohnson#aol.com
Gender: M
FirstName: Sue
LastName: Smith
PhoneNumber: 987-654-3210
FaxNumber: 222-222-2222
EmailAddress: ssmith#comcast.net
Gender: F
Instead, it's displaying this:
versionDate: 2011-10-04
versionNumber: 1.0
versionDate#text - 2011-10-04Contact info: False#text - 2011-10-04versionNumber#text - 2011-10-04Contact info: False#text - 2011-10-04ContactFirstName - 2011-10-04Contact info: False#text - 2011-10-04ContactFirstName - 2011-10-04Contact info: False#text - 2011-10-04ContactFirstName - 2011-10-04Contact info: False#text - 2011-10-04ContactFirstName - 2011-10-04Contact info: False#text - 2011-10-04ContactFirstName - 2011-10-04Contact info:
I've tried making another XmlNodeList that's a child of the child, but it's not liking the syntax, so I need to know how to get down to the next level of information.
I have attached the XML and C# file below.
<Contacts>
<versionDate>2011-10-04</versionDate>
<versionNumber>1.0</versionNumber>
<Contact Gender ="M">
<FirstName>Bob</FirstName>
<LastName>Johnson</LastName>
<PhoneNumber>123-456-7890</PhoneNumber>
<FaxNumber>111-111-1111</FaxNumber>
<EmailAddress>bjohnson#aol.com</EmailAddress>
</Contact>
<Contact Gender ="F">
<FirstName>Sue</FirstName>
<LastName>Smith</LastName>
<PhoneNumber>987-654-3210</PhoneNumber>
<FaxNumber>222-222-2222</FaxNumber>
<EmailAddress>ssmith#comcast.net</EmailAddress>
</Contact>
</Contacts>
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
string results = "";
private void button1_Click(object sender, EventArgs e)
{
string fileName = Application.StartupPath + "\\XMLFile1.xml";
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(fileName);
XmlElement elm = xmlDoc.DocumentElement;
results += elm.FirstChild.Name + ": " + elm.FirstChild.InnerText + Environment.NewLine;
results += elm.FirstChild.NextSibling.Name + ": " + elm.FirstChild.NextSibling.InnerText + Environment.NewLine;
XmlNodeList contactInfo = elm.ChildNodes;
for (int count = 0; count < contactInfo.Count; count++)
{
results += (contactInfo[count].Name);
results += (contactInfo[count].FirstChild.Name + " - " + contactInfo[0].FirstChild.InnerText);
results += ("Contact info: " + contactInfo[0].FirstChild.HasChildNodes.ToString());
XmlNodeList contactProperties = contactInfo[0].ChildNodes;
for (int counter = 0; counter < contactProperties.Count; counter++)
{
results += (contactProperties[counter].Name + " - " + contactProperties[counter].InnerText);
}
}
textBox1.Text += results;
}
}
Any and all help will be greatly appreciated! Thank you!
Recursion should work:
public string CompileResults(XElement e)
{
string retVal = String.Format("{0}:{1} ", e.Name, e.Value);
foreach (XAttribute xa in e.Attributes())
retVal += String.Format("{0}:{1} ", xa.Name, xa.Value);
foreach (XElement xe in e.Elements())
retVal += CompileResults(xe); ;
return retVal;
}
private void button1_Click(object sender, EventArgs e)
{
string fileName = Application.StartupPath + "\\XMLFile1.xml";
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(fileName);
string results = CompileResults(xmlDoc.FirstChild);
}
I'd do something like this:
public static void DumpXml(XElement root, TextWriter writer)
{
if (root.HasElements)
{
foreach (var child in root.Elements())
{
DumpXml(child, writer);
}
}
else
{
writer.WriteLine("{0}: {1}", root.Name, root.Value);
}
foreach (var attr in root.Attributes())
{
writer.WriteLine("{0}: {1}", attr.Name, attr.Value);
}
}
Then use it:
var doc = XDocument.Load(xmlPath);
var writer = new StringWriter();
DumpXml(doc.Root, writer);
var result = writer.ToString();