How do I store values from textbox in C# - 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>

Related

Child node is repeating, can't get it to work

i have an xml code that create an xml file and this works great however i am a bit confused on why one of the parent node still opens and it does not group by employee first ( the employee hours and workdays should only open up once as long as the employee id is the same and close at the end when all days have been created) see attached code `
// Create a new <Employees> element and add it to the root node
XmlElement Employees = xmlDoc.CreateElement("employees");
xmlDoc.DocumentElement.AppendChild(Employees);
// Create a new <staffingHours> element and add it to the root node
XmlElement parentNode = xmlDoc.CreateElement("CompanyHours");
// Set attribute name and value!
parentNode.SetAttribute("processType", "merge");
xmlDoc.DocumentElement.PrependChild(parentNode);
string catid = "";
string nurseCode = GridView1.Rows[0].Cells[0].Text;
foreach ( GridViewRow row in GridView1.Rows)
{
//first part of EMPLOYEES ELEMENTS AND CHILD ELEMENTS
string fromFormat = "MM/dd/yyyy";
string toFormat = "yyyy-MM-dd";
if (catid != row.Cells[0].Text)
{
XmlElement employee = xmlDoc.CreateElement("employee");
xmlDoc.DocumentElement.AppendChild(employee);
Employees.AppendChild(employee);
//create the element
XmlElement NurseId1 = xmlDoc.CreateElement("employeeId");
employee.AppendChild(NurseId1);
NurseId1.InnerText = row.Cells[0].Text;
XmlElement HireDate1 = xmlDoc.CreateElement("hireDate");
employee.AppendChild(HireDate1);
DateTime newdate = DateTime.ParseExact(row.Cells[6].Text, fromFormat, null);
HireDate1.InnerText = newdate.ToString(toFormat);//row.Cells[6].Text;
xmlDoc.DocumentElement.InsertAfter(Employees, xmlDoc.DocumentElement.LastChild);
}
XmlElement EmployeeHours = xmlDoc.CreateElement("EmployeeHours");
if (catid != row.Cells[0].Text)
{
XmlElement NurseId = xmlDoc.CreateElement("employeeId");
staffHours.AppendChild(NurseId);
NurseId.InnerText = row.Cells[0].Text;
}
XmlElement WorkDays = xmlDoc.CreateElement("workDays");
XmlElement WorkDay = xmlDoc.CreateElement("workDay");
//Third node and data source
XmlElement Date = xmlDoc.CreateElement("date");
WorkDay.AppendChild(Date);
DateTime converteddate = DateTime.ParseExact(row.Cells[1].Text,
fromFormat, null);
Date.InnerText = converteddate.ToString(toFormat);
XmlElement hourEntries = xmlDoc.CreateElement("hourEntries");
xmlDoc.DocumentElement.PrependChild(hourEntries);
WorkDay.AppendChild(hourEntries);
XmlElement HourEntry = xmlDoc.CreateElement("hourEntry");
xmlDoc.DocumentElement.PrependChild(HourEntry);
hourEntries.AppendChild(HourEntry);
//Fourth node and data source
XmlElement Hours = xmlDoc.CreateElement("hours");
HourEntry.AppendChild(Hours);
Hours.InnerText = row.Cells[2].Text;
XmlElement JobTitleCode = xmlDoc.CreateElement("jobTitleCode");
HourEntry.AppendChild(JobTitleCode);
JobTitleCode.InnerText = row.Cells[3].Text;
XmlElement payTypeCode = xmlDoc.CreateElement("payTypeCode");
HourEntry.AppendChild(payTypeCode);
payTypeCode.InnerText = row.Cells[4].Text;
staffHours.AppendChild(WorkDays);
WorkDays.AppendChild(WorkDay);
parentNode.AppendChild(EmployeeHours);
xmlDoc.DocumentElement.InsertAfter(parentNode,
xmlDoc.DocumentElement.LastChild);
catid = row.Cells[0].Text;}
now once this code runs it create the attached image but i don't want the highlighted lines repeating inside the same parent node...
[1]: https://i.stack.imgur.com/eirsv.png
My issue was the element was inside of my loop i needed a new set of eyes to look into this. Good catch Tamas Szabo. issue is resolved.

how to extract particular attribute from xml file using c#?

static void Main(string[] args)
{
WebClient _httpReq = new WebClient(); // to talk to the web only for get method
string response = _httpReq.DownloadString("https://open-ic.epic.com/FHIR/api/FHIR/DSTU2/Patient?family=Argonaut&given=Jason");
Console.WriteLine(response);\\prints the xml string fetched from FHIR provider EPIC
XmlDocument xml = new XmlDocument();
xml.LoadXml(response); // suppose that myXmlString contains "<Names>...</Names>"
XmlNodeList xnList = xml.SelectNodes("/entry/resource/patient/name");
// here code is trying to extract the name attribute
foreach (XmlNode xn in xnList)
{
string firstName = xn["family value"].InnerText;
string lastName = xn["given value"].InnerText;
Console.WriteLine("Name: {0} {1}", firstName, lastName);
//print the first name and last name of the patient
}
Console.ReadLine();
}
i do it like this:
XmlDocument MyDocument = new XmlDocument();
MyDocument.Load("...");
XmlNode MyNode = MyDocument.SelectSingleNode("/Node_Name");
foreach (XmlAttribute MyAttribute in MyNode.Attributes)
{
if (MyAttribute.Name == "Attribute_Name")
{
object Value = MyAttribute.Value;
break;
}
}
Review XPath. Once you start understanding it, you will find it efficient and easier to code than iterating through lists. It also lets you directly get the nodes/attributes you want.
Then the code would be something similar to
string attrVal = doc.SelectSingleNode("/entry/resource/patient/#name").Value;
Or you can Load XML in XMlDocument and You can fetch element and out of that element you can read specific atairbute,
XmlDocument doc = new XmlDocument();
doc.LoadXml("<reply success=\"true\">More nodes go here</reply>");
XmlElement root = doc.DocumentElement;
string s = root.Attributes["success"].Value;

xml nodes editing based on an xmlElement

I have tried two ways but they both didnt work..
the first way::
string filepath = Server.MapPath[this is not a link]("XMLFile2.xml");
XmlDocument xdoc = new XmlDocument();
xdoc.Load(filepath);
XmlNode root = xdoc.DocumentElement;
XmlNode idNode = root.SelectSingleNode("/students/student/id");
if (idNode.Value == 9.ToString())
{
var nodeOfStudent = xdoc.SelectNodes("/students/student[#id='9']");
nodeOfStudent[1].InnerXml = TextBox_firstname.Text;
nodeOfStudent[2].InnerXml = TextBox_lastname.Text;
nodeOfStudent[3].InnerXml = TextBox_dob.Text;
nodeOfStudent[4].InnerXml = TextBox_class.Text;
nodeOfStudent[5].InnerXml = TextBox_section.Text;
nodeOfStudent[6].InnerXml = TextBox_telephone.Text;
}
the second way::
string filepath = Server.MapPath("XMLFile2.xml");
XmlDocument xdoc = new XmlDocument();
xdoc.Load(filepath);
XmlNode root = xdoc.DocumentElement;
XmlNode idNode = root.SelectSingleNode("/students/student/id");
xdoc.SelectSingleNode("/students/student[#id='10']/firstname").InnerXml = TextBox_firstname.Text;
xdoc.DocumentElement.AppendChild(firstname);
xdoc.SelectSingleNode("/students/student[#id='10']/lastname").InnerXml = TextBox_firstname.Text;
xdoc.SelectSingleNode("/students/student[#id='10']/dob").InnerXml = TextBox_firstname.Text;
xdoc.SelectSingleNode("/students/student[#id='10']/class").InnerXml = TextBox_firstname.Text;
xdoc.SelectSingleNode("/students/student[#id='10']/section").InnerXml = TextBox_firstname.Text;
xdoc.SelectSingleNode("/students/student[#id='10']/telephone").InnerXml = TextBox_firstname.Text;
xdoc.Save(filepath);
is there something wrong i dont see...
my xml file looks like this::
<students>
<student>
<id>1</id>
<first_name>ahmad</first_name>
<last_name>hani</last_name>
<DOB>12/5/1998</DOB>
<class>sixth</class>
<section>A</section>
<telephone>06555632</telephone>
</student>
</students>
and i used a query string to load the values from a gridView located in another page using "QueryString"....
thanks in advance.
You can easily do this with Linq to xml:
int id = 9;
XDocument xdoc = XDocument.Load(filepath);
var student = xdoc.Descendants("student")
.Where(s => (int)s.Element("id") == id)
.SingleOrDefault();
if (student != null)
{
student.Element("first_name").Value = TextBox_firstname.Text;
student.Element("last_name").Value = TextBox_lastname.Text;
student.Element("DOB").Value = TextBox_dob.Text;
student.Element("class").Value = TextBox_class.Text;
// etc
}
xdoc.Save(filepath);

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);
}

Sharepoint via web service : checking if item exists in list

Because Microsoft did not include a way to have unique constraints in sharepoint, this has to be done manually.
I am inserting items into a sharepoint list via a web service method.
How can I check if an existing list item already exists with the same field ID value?
I've learnt I should be using wsLists.getListitems web service method, but its not exactly "user friendly". MSDN documentation is again not really great at explaining what should be an easy thing to do.
private bool itemDoesntExist()
{
XmlDocument doc = new XmlDocument();
doc.LoadXml("<Document><Query><Where><Contains><FieldRef Name=\"ID\" /><Value Type=\"Text\">" + this.ID + "</Value></Contains></Where></Query><ViewFields /><QueryOptions /></Document>");
XmlNode listQuery = doc.SelectSingleNode("//Query");
XmlNode listViewFields = doc.SelectSingleNode("//ViewFields");
XmlNode listQueryOptions = doc.SelectSingleNode("//QueryOptions");
XmlNode items = this.wsLists.GetListItems(this.ListName , string.Empty, listQuery, listViewFields, string.Empty, listQueryOptions, null);
if (items.ChildNodes[1].Attributes["ItemCount"].Value == "0")
{
return true;
}
else
{
return false;
}
}
Here's a procedure I wrote 2 years ago that pulls the ID of a document with a given filename... I think you could easily revise it to return true/false if a given ID exists in a list.
protected string GetDocumentID(Lists.Lists ls, string ListGUID, string FileName)
{
string strDocumentID = "-1";
string strViewGUID = "";
string strRowLimit = "50000";
XmlDocument xmlDoc = new XmlDocument();
XmlNode query = xmlDoc.CreateNode(XmlNodeType.Element, "Query", "");
XmlNode viewFields = xmlDoc.CreateNode(XmlNodeType.Element, "ViewFields", "");
XmlNode queryOptions = xmlDoc.CreateNode(XmlNodeType.Element, "QueryOptions", "");
query.InnerXml = "";
viewFields.InnerXml = "";
queryOptions.InnerXml = "<IncludeAttachmentUrls>TRUE</IncludeAttachmentUrls>";
System.Xml.XmlNode nodeListItems = ls.GetListItems(ListGUID, strViewGUID, query, viewFields, strRowLimit, queryOptions, null);
XmlDocument doc = new XmlDocument();
doc.LoadXml(nodeListItems.InnerXml);
XmlNamespaceManager nsmgr = new XmlNamespaceManager(doc.NameTable);
nsmgr.AddNamespace("z", "#RowsetSchema");
nsmgr.AddNamespace("rs", "urn:schemas-microsoft-com:rowset");
foreach (XmlNode node in doc.SelectNodes("/rs:data/z:row", nsmgr))
{
if (node.Attributes["ows_LinkFilename"].Value == FileName)
{
strDocumentID = node.Attributes["ows_ID"].Value;
break;
}
}
return strDocumentID;
}
Here's the code that calls it...
Lists.Lists ls = new Lists.Lists();
ls.PreAuthenticate = true;
ls.Credentials = System.Net.CredentialCache.DefaultCredentials;
ls.Url = SharePointSiteURL + #"/_vti_bin/lists.asmx";
string DocID = GetDocumentID(ls, ListGUID, FileName);

Categories