Here I am trying to read the TID Value and I am able to read the Value(Intially it is 1)..and every time I need to increment by one and update to TID node value
protected void Page_Load(object sender, EventArgs e)
{
XmlDocument xml = new XmlDocument();
xml.Load(Server.MapPath("~/XmlFile1.xml"));
XmlNode node = xml.SelectSingleNode("AllID/ID/TID");
int s = Convert.ToInt32( node.InnerText);
node.InnerText= s++.ToString();
xml.Save(Server.MapPath("~/XmlFile1.xml"));
}
But here it is not updating the TID value
<AllID>
<ID>
<TID>1</TID>
</ID>
</AllID>
XmlDocument xml = new XmlDocument();
xml.Load(Server.MapPath("~/XmlFile1.xml"));
XmlNode node = xml.SelectSingleNode("AllID/ID/TID");
int s = Convert.ToInt32( node.InnerText);
node.InnerText = (++s).ToString(); //Increment and make string
xml.Save(Server.MapPath("~/XmlFile1.xml"));
What about node.InnerText = s++.ToString();? I haven't tested it.
Related
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>
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>
I plan to retrieve each suggestion in array and then stroe it in to the list. I have trouble retrieve the option node data, in this pattern {aeroplane,aeroplanes, aerobian} {i}, Any kind soul can help me out with it.
XmlDocument findStringDoc = new XmlDocument();
findStringDoc.Load (Application.dataPath+ "/" + filename);
XmlNodeList nodeList = findStringDoc.SelectNodes("/results/error");
//XmlNodeList suggestionNodeList = findStringDoc.SelectNodes("/results/error/suggestions/option");
foreach(XmlNode xn in nodeList){
errorString.Add(xn["string"].InnerText);
errorType.Add(xn["type"].InnerText);
//string temp = xn["suggestion"].InnerXml;
////TODO: Retrieve suggestions here!
XmlNodeList suggestionNodeList = findStringDoc.SelectNodes("/suggestions");
foreach(XmlNode yn in suggestionNodeList){
option[suggestionNodeList.Count] = yn["option"].InnerText;
Debug.Log(yn["option"].InnerText);
}
suggestionResult.Add (option);
//Debug.Log(suggestionResult);
//XmlNodeList suggestionNodeList = findStringDoc.SelectNodes("/results/error[string='{0}']/suggestions/option",errorString[i]);
}
<results>
<error>
<string>aeroplan</string>
<description>Spelling</description>
<precontext>a</precontext>
<suggestions>
<option>aeroplane</option>
<option>aeroplanes</option>
<option>aerobian</option>
</suggestions>
<type>spelling</type>
</error>
<error>
<string>i</string>
<description>Make I uppercase</description>
<precontext></precontext>
<suggestions>
<option>I</option>
</suggestions>
<type>grammar</type>
<url>http://service.afterthedeadline.com/info.slp?text=i&tags=PRP&engine=1</url>
</error>
</results>
You can use my code below:
private static void GetSuggestionOption(string filename, string value, string optionSuggest)
{
XDocument xDoc = XDocument.Parse(filename);
var parentNode = xDoc.Descendants().Where(x => x.Value == value).Ancestors().FirstOrDefault();
var childNode = parentNode.Descendants().Where(x => x.Name == optionSuggest);
childNode.ToList().ForEach(x => Console.WriteLine(x.Value));
}
Calling: GetSuggestionOption(fileName, "aeroplan", "option");
Happy Coding!
You can use XmlDocument.SelectNodes() method passing suitable XPath string parameter to select specific element(s) from XmlDocument, for example :
public void GetSuggestionOption(string keyword)
{
XmlDocument doc = new XmlDocument();
doc.Load (Application.dataPath+ "/" + filename);
string xpath = string.Format("//error[string='{0}']/suggestions/option", keyword);
XmlNodeList optionSuggestionList = doc.SelectNodes(xpath);
foreach (XmlNode option in optionSuggestionList)
{
Debug.Log(option.InnerXml);
}
}
You can call the method this way for example : GetSuggestionOption("aeroplan")
I want to delete selected row and update the xml file and then load the grid view with updated data. When debugging I get null value for nodelist.
This is my xml file
<?xml version="1.0" encoding="utf-8" ?>
<PERSONES>
<person>
<name>Dilan Perera</name>
<age>22</age>
</person>
<person>
<name>Thusitha Badde</name>
<age>24</age>
</person>
</PERSONES>
Here is the button click event. The problem is I get null value for nodelist
protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
GridViewRow row = (GridViewRow)GridView1.Rows[e.RowIndex];
string age = row.Cells[2].Text.Trim(); // i get correct value for age here
XmlDocument doc2 = new XmlDocument();
doc2.Load(Server.MapPath("names.xml"));
XmlNode nodeList = doc2.SelectSingleNode(string.Format("PERSONES/person[#age='{0}']", age));
doc2.DocumentElement.RemoveChild(nodeList);
doc2.Save(Server.MapPath("names.xml"));
getdata();
}
The xpath query is incorrect, # means attribute, so remove # in the age check, then it will filter the element.
protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
GridViewRow row = (GridViewRow)GridView1.Rows[e.RowIndex];
string age = row.Cells[2].Text.Trim(); // i get correct value for age here
XmlDocument doc2 = new XmlDocument();
doc2.Load(Server.MapPath("names.xml"));
XmlNode nodeList = doc2.SelectSingleNode(string.Format("PERSONES/person[age='{0}']", age));
doc2.DocumentElement.RemoveChild(nodeList);
doc2.Save(Server.MapPath("names.xml"));
getdata();
}
I have just tested this and it works.
XmlDocument doc2 = new XmlDocument();
doc2.Load(Server.MapPath("names.xml"));
XmlNode ageNode = doc2.SelectSingleNode(string.Format("//PERSONES/person/age[text() = '{0}']", age));
if (ageNode != null)
{
var personNode = ageNode.ParentNode;
doc2.DocumentElement.RemoveChild(personNode);
doc2.Save(Server.MapPath("names.xml"));
}
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;
}