C# how can i get all users of the XML file - c#

I have created an xml file and there are stored my user. The problem, I only ever get the first one out. How do I manage to get all users of the XML file displayed?
private void button1_Click(object sender, EventArgs e)
{
string path = "C:\\temp\\Accounts.xml";
XmlDocument doc = new XmlDocument();
doc.Load(path);
XmlElement root = doc.CreateElement("Login");
XmlElement user = doc.CreateElement("user");
user.InnerText = textBox1.Text;
root.AppendChild(user);
doc.DocumentElement.AppendChild(root);
doc.Save(path);
MessageBox.Show("Created SuccesFully!");
}
private void button2_Click(object sender, EventArgs e)
{
XmlDocument xdoc = new XmlDocument();
xdoc.Load("C:\\temp\\Accounts.xml");
foreach (XmlNode person in xdoc.SelectNodes("/Login"))
{
MessageBox.Show(person["user"].InnerText);
}
}

I'm not sure what wasn't working for you, but this works for me. I am using //Login as the path selector. Ensure that your XML file actually has multiple users.
void Main()
{
//Create();
View();
// Output:
// User1
// User2
}
private void Create()
{
string path = "C:\\Code\\Sandbox\\Accounts.xml";
XmlDocument doc = new XmlDocument();
doc.Load(path);
XmlElement root = doc.CreateElement("Login");
XmlElement user = doc.CreateElement("user");
user.InnerText = "User2";
root.AppendChild(user);
doc.DocumentElement.AppendChild(root);
doc.Save(path);
Console.WriteLine("Created SuccesFully!");
}
private void View()
{
XmlDocument xdoc = new XmlDocument();
xdoc.Load("C:\\Code\\Sandbox\\Accounts.xml");
foreach (XmlNode person in xdoc.SelectNodes("//Login"))
{
Console.WriteLine(person["user"].InnerText);
}
}
Here is the generated XML. I inserted a root Logins element.
<Logins>
<Login>
<user>User1</user>
</Login>
<Login>
<user>User2</user>
</Login>
</Logins>

Related

UPdating XML, getting "Object Reference Not Set To An Instance Of An Object"

I am trying to update 3 pieces of data in an XML document but getting an "Object Reference Not Set To An Instance Of An Object" error. This is the XML file format I am trying to update:
<?xml version="1.0" encoding="US-ASCII" standalone="true"?>
<ExportSettings xmlns="CompanyName" ExportName="Data Export" Dataset="TestName">
<General>
<AsOfDate>03/31/15</AsOfDate>
<PriceDate>03/31/16</PriceDate>
</General>
<Source>
<Set>Set Name</Set>
</Source>
</ExportSettings>
This is the C# code that is throwing the error:
private void btnUpdate_Click(object sender, EventArgs e)
{
try
{
{
string strAsOfDate = dateTimePickerAsOfDate.Text;
string strPriceDate = dateTimePickerPriceDate.Text;
string strSetName = txtboxSet.Text;
XmlDocument doc = new XmlDocument();
doc.Load(strXMLfilepath);
XmlNode General;
XmlNode root = doc.DocumentElement;
General = root.SelectSingleNode("/ExportSettings/General");
General["AsOfDate"].InnerText = strAsOfDate;
General["PriceDate"].InnerText = strPriceDate;
XmlNode Source;
Source = root.SelectSingleNode("/ExportSettings/Source");
Source["Set"].InnerText = strSetName;
doc.Save(strXMLfilepath);
}
}
catch (System.Exception excep)
{
MessageBox.Show(excep.Message);
}
}
Can anyone see the problem? I am not very familiar with updating XML so there may be something basic wrong here.
I've debugged this locally and as Pawel suggests, you need to make some changes regarding namespaces:
private void btnUpdate_Click(object sender, EventArgs e)
{
try
{
{
string strAsOfDate = dateTimePickerAsOfDate.Text;
string strPriceDate = dateTimePickerPriceDate.Text;
string strSetName = txtboxSet.Text;
XmlDocument doc = new XmlDocument();
doc.Load(strXMLfilepath);
XmlNamespaceManager nsmgr = new XmlNamespaceManager(doc.NameTable);
nsmgr.AddNamespace("ab", "CompanyName");
XmlNode General;
XmlNode root = doc.DocumentElement;
General = root.SelectSingleNode("//ab:General", nsmgr);
General["AsOfDate"].InnerText = strAsOfDate;
General["PriceDate"].InnerText = strPriceDate;
doc.Save(strXMLfilepath);
}
}
catch (System.Exception excep)
{
MessageBox.Show(excep.Message);
}
}
Hope this helps.

How do I store values from textbox in C#

I created this program to get texts from textboxes and store in a xml file but it doesn't store. Also if I close the form and reopen it and enter data again how can it update the same existing file without replacing the previous data.? please fix my code
private void button1_Click(object sender, EventArgs e)
{
string name = this.txtName.Text;
string occupation = this.txtOccupation.Text;
string dob = this.txtDob.Text;
string nic = this.txtNic.Text;
double id = double.Parse(this.lblID.Text);
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.CreateXmlDeclaration("1.0", "utf-8", "yes");
XmlNode rootNode = xmlDoc.CreateElement("Users");
XmlNode subNode = xmlDoc.CreateElement("Users");
XmlAttribute nameAtt = xmlDoc.CreateAttribute("Name");
nameAtt.Value = name;
XmlAttribute occupationAtt = xmlDoc.CreateAttribute("Occupation");
occupationAtt.Value = occupation;
XmlAttribute dobAtt = xmlDoc.CreateAttribute("Date of Birth");
dobAtt.Value = dob;
XmlAttribute nicAtt = xmlDoc.CreateAttribute("NIC");
nicAtt.Value = nic;
XmlAttribute idAtt = xmlDoc.CreateAttribute("ID");
idAtt.Value = idAtt.ToString();
subNode.Attributes.Append(nameAtt);
subNode.Attributes.Append(occupationAtt);
subNode.Attributes.Append(dobAtt);
subNode.Attributes.Append(nicAtt);
subNode.Attributes.Append(idAtt);
rootNode.AppendChild(subNode);
subNode.AppendChild(rootNode);
xmlDoc.Save("E:/Data.xml");
Hide();
}
}
}
This is just a simple working example based on the code you provided, but probably there are better ways to accomplish what you are trying to do:
private void button1_Click(object sender, EventArgs e)
{
string name = this.txtName.Text;
string occupation = this.txtOccupation.Text;
string dob = this.txtDob.Text;
string nic = this.txtNic.Text;
double id = double.Parse(this.lblID.Text);
// XML file path.
string xmlPath = "E:/Data.xml";
XmlDocument xmlDoc = new XmlDocument();
// If specified file does not exist, create a new one.
if (!File.Exists(xmlPath))
{
XmlDeclaration xmlDeclaration = xmlDoc.CreateXmlDeclaration("1.0", "UTF-8", "yes");
XmlElement rootNode = xmlDoc.DocumentElement;
xmlDoc.InsertAfter(xmlDeclaration, rootNode);
XmlNode parentNode = xmlDoc.CreateElement("Users");
XmlNode subNode = xmlDoc.CreateElement("User");
XmlAttribute nameAtt = xmlDoc.CreateAttribute("Name");
nameAtt.Value = name;
XmlAttribute occupationAtt = xmlDoc.CreateAttribute("Occupation");
occupationAtt.Value = occupation;
XmlAttribute dobAtt = xmlDoc.CreateAttribute("Date_Of_Birth");
dobAtt.Value = dob;
XmlAttribute nicAtt = xmlDoc.CreateAttribute("NIC");
nicAtt.Value = nic;
XmlAttribute idAtt = xmlDoc.CreateAttribute("ID");
idAtt.Value = id.ToString();
subNode.Attributes.Append(nameAtt);
subNode.Attributes.Append(occupationAtt);
subNode.Attributes.Append(dobAtt);
subNode.Attributes.Append(nicAtt);
subNode.Attributes.Append(idAtt);
xmlDoc.AppendChild(parentNode);
parentNode.AppendChild(subNode);
// Save new XML file.
xmlDoc.Save(xmlPath);
}
// If specified file exists, read and update it.
else
{
// Open existing XML file.
xmlDoc.Load(xmlPath);
// Set to true if current name is already found in the XML file,
// of course it should be better to check the ID instead the name,
// supposing that ID is unique.
bool nameFound = false;
// Get all "User" nodes and check if one of them already contains
// the specified name.
foreach (XmlNode user in xmlDoc.SelectNodes("Users/User"))
{
if (user.Attributes.GetNamedItem("Name").Value == name)
{
nameFound = true;
break;
}
}
// If the name is not already in the file, insert a new user
// with that name.
if (nameFound == false)
{
XmlNode subNode = xmlDoc.CreateElement("User");
XmlAttribute nameAtt = xmlDoc.CreateAttribute("Name");
nameAtt.Value = name;
XmlAttribute occupationAtt = xmlDoc.CreateAttribute("Occupation");
occupationAtt.Value = occupation;
XmlAttribute dobAtt = xmlDoc.CreateAttribute("Date_Of_Birth");
dobAtt.Value = dob;
XmlAttribute nicAtt = xmlDoc.CreateAttribute("NIC");
nicAtt.Value = nic;
XmlAttribute idAtt = xmlDoc.CreateAttribute("ID");
idAtt.Value = id.ToString();
subNode.Attributes.Append(nameAtt);
subNode.Attributes.Append(occupationAtt);
subNode.Attributes.Append(dobAtt);
subNode.Attributes.Append(nicAtt);
subNode.Attributes.Append(idAtt);
xmlDoc.SelectSingleNode("Users").AppendChild(subNode);
xmlDoc.Save(xmlPath);
}
}
}
And this is a sample output XML file:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<Users>
<User Name="John" Occupation="student" Date_Of_Birth="1990" NIC="NIC" ID="123" />
<User Name="David" Occupation="professor" Date_Of_Birth="1973" NIC="NIC" ID="452" />
</Users>

C# crashes on save (doc.Save(PATH);)

This program crashes on debug and highlights the "doc.Save(PATH);" at the end of the code.
I am trying to save the variables cookieScore, additionAddition, and additionMultiplier into an XML file.
I am getting information about it from here "http://visualcsharptutorials.com/net-framework/writing-xml-file"
private XmlDocument doc;
string PATH = #"C:\sample.xml";
private void saveBtn_Click(object sender, EventArgs e)
{
doc = new XmlDocument();
if (!System.IO.File.Exists(PATH))
{
XmlDeclaration declaration = doc.CreateXmlDeclaration("1.0", "UTF-8", "yes");
XmlComment comment = doc.CreateComment("This is saved game data");
XmlElement root = doc.CreateElement("data");
XmlElement data = doc.CreateElement("data");
XmlAttribute addition = doc.CreateAttribute("addition");
XmlElement additionNumber = doc.CreateElement("additionNumber");
XmlElement multiplicationNumber = doc.CreateElement("multiplicationNumber");
XmlElement cookieSave = doc.CreateElement("cookieSave");
addition.Value = "addition";
additionNumber.InnerText = additionAddition.ToString();
multiplicationNumber.InnerText = additionMultiplier.ToString();
cookieSave.InnerText = cookieScore.ToString();
doc.AppendChild(declaration);
doc.AppendChild(comment);
doc.AppendChild(root);
root.AppendChild(data);
data.Attributes.Append(addition);
data.AppendChild(cookieSave);
data.AppendChild(additionNumber);
data.AppendChild(multiplicationNumber);
doc.Save(PATH);
}
else
{
}
My guess is you're getting an access related exception because you're trying to write to the root of your C drive. Try writing to your desktop instead:
string PATH = #"C:\Users\[yourusername]\Desktop\sample.xml";
Another option would be to try to run your EXE as admin. If it works, then you know that's your problem.

c# winforms Form Load ComboBox DropDownList get value from XML file

XML File:
<?xml version="1.0" encoding="utf-16"?>
<XMLFILE>
<Active>0</Active>
<Hits_Method>1</Hits_Method>
</XMLFILE>
What i'm trying to do is on Form1_Load get the value of ComboBox4 from XML File (Hits_Method) and when the program start to show me the value. i try something like this but didn't work out
// ------------------- StartUP Load
private void Form1_Load(object sender, EventArgs e)
{
// --------------- Read XML File / Data: Settings_Ads_General
String xmlfile = "Settings_General.xml";
XmlTextReader xreader = new XmlTextReader(xmlfile);
string comboBox4Value = xreader.GetAttribute("Hits_Method");
comboBox4.SelectedIndex = comboBox4Value;
}
Try this instead:
private void Form1_Load(object sender, EventArgs e)
{
// --------------- Read XML File / Data: Settings_Ads_General
String xmlfile = "Settings_General.xml";
XmlDocument doc = new XmlDocument();
doc.Load(xmlfile);
string comboBox4Value = doc.SelectSingleNode("XMLFILE/Hits_Method").InnerText;
comboBox4.SelectedIndex = Convert.ToInt32(comboBox4Value);
}
The SelectSingleNode method extracts data based on an XPath expression. And "XMLFILE/Hits_Method" is the XPath that leads to your value.
I will use XmlDocument and XmlNode classes.
{
String sPath = "file.xml"
XmlDocument doc = new XmlDocument();
doc.Load(sPath)
XmlNode node = doc.SelectSingleNode("XMLFILE/Hits_Method");
if (node != null)
comboBox4.SelectedIndex = node.InnerText;
}

populate a tree view with an xml file

Im using .net windows form application. I have an xml file.I want to populate a tree view with data from a xml file. I am doing this using the following code.
private void button1_Click(object sender, EventArgs e)
{
try
{
this.Cursor = System.Windows.Forms.Cursors.WaitCursor;
//string strXPath = "languages";
string strRootNode = "Treeview Sample";
OpenFileDialog Dlg = new OpenFileDialog();
Dlg.Filter = "All files(*.*)|*.*|xml file (*.xml)|*.txt";
Dlg.CheckFileExists = true;
string xmlfilename = "";
if (Dlg.ShowDialog() == DialogResult.OK)
{
xmlfilename = Dlg.FileName;
}
// Load the XML file.
//XmlDocument dom = new XmlDocument();
//dom.Load(xmlfilename);
XmlDocument doc = new XmlDocument();
doc.Load(xmlfilename);
string rootName = doc.SelectSingleNode("/*").Name;
textBox4.Text = rootName.ToString();
//XmlNode root = dom.LastChild;
//textBox4.Text = root.Name.ToString();
// Load the XML into the TreeView.
this.treeView1.Nodes.Clear();
this.treeView1.Nodes.Add(new TreeNode(strRootNode));
TreeNode tNode = new TreeNode();
tNode = this.treeView1.Nodes[0];
XmlNodeList oNodes = doc.SelectNodes(textBox4.Text);
XmlNode xNode = oNodes.Item(0).ParentNode;
AddNode(ref xNode, ref tNode);
this.treeView1.CollapseAll();
this.treeView1.Nodes[0].Expand();
this.Cursor = System.Windows.Forms.Cursors.Default;
}
catch (Exception ex)
{
this.Cursor = System.Windows.Forms.Cursors.Default;
MessageBox.Show(ex.Message, "Error");
}
}
private void AddNode(ref XmlNode inXmlNode, ref TreeNode inTreeNode)
{
// Recursive routine to walk the XML DOM and add its nodes to a TreeView.
XmlNode xNode;
TreeNode tNode;
XmlNodeList nodeList;
int i;
// Loop through the XML nodes until the leaf is reached.
// Add the nodes to the TreeView during the looping process.
if (inXmlNode.HasChildNodes)
{
nodeList = inXmlNode.ChildNodes;
for (i = 0; i <= nodeList.Count - 1; i++)
{
xNode = inXmlNode.ChildNodes[i];
inTreeNode.Nodes.Add(new TreeNode(xNode.Name));
tNode = inTreeNode.Nodes[i];
AddNode(ref xNode, ref tNode);
}
}
else
{
inTreeNode.Text = inXmlNode.OuterXml.Trim();
}
}
My xml file is this:"hello.xml"
<?xml version="1.0" encoding="utf-8" ?>
<languages>
<language>
<key>abc</key>
<value>hello how ru</value>
</language>
<language>
<key>def</key>
<value>i m fine</value>
</language>
<language>
<key>ghi</key>
<value>how abt u</value>
</language>
</languages>
Now after using the above code I am able to populate the tree view. But I dont like to populate the complete xml file. I should get only till
languages
language
key
value
I don't want
abc
how are you
etc.....
I mean to say the leaf nodes. Please help me
What you don't want to add is the text content of the nodes, if I understood correctly; then, you might check the NodeType property of the XmlNode class, something like:
xNode = inXmlNode.ChildNodes[i];
if (xNode.NodeType != XmlNodeType.Text) {
inTreeNode.Nodes.Add(new TreeNode(xNode.Name));
tNode = inTreeNode.Nodes[i];
AddNode(ref xNode, ref tNode);
}

Categories