Writing xml and reading it back c# with xample xml output - c#

Ok I am using again xmldocument to write an xml file then read it back in simple right but how to get the age this time in this example? I was asked to produce the whole problem before so here it is.
private void button1_Click(object sender, EventArgs e)
{
XmlDocument xmlDoc = new XmlDocument();
XmlNode rootNode = xmlDoc.CreateElement("users");
xmlDoc.AppendChild(rootNode);
XmlNode userNode = xmlDoc.CreateElement("user");
XmlAttribute attribute = xmlDoc.CreateAttribute("age");
attribute.Value = "42";
userNode.Attributes.Append(attribute);
userNode.InnerText = "John Doe";
rootNode.AppendChild(userNode);
userNode = xmlDoc.CreateElement("user");
attribute = xmlDoc.CreateAttribute("age");
attribute.Value = "39";
userNode.Attributes.Append(attribute);
userNode.InnerText = "Jane Doe";
rootNode.AppendChild(userNode);
xmlDoc.Save("c:\\temp\\testdoc.xml");
}
private void button2_Click(object sender, EventArgs e)
{
string files = "c:\\temp\\testdoc.xml";
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(files);
foreach (XmlNode node in xmlDoc)
{
MessageBox.Show(node.SelectSingleNode("user").InnerText);
MessageBox.Show(node.SelectSingleNode("age").InnerText);
}
}
I can read the users name correctly but not the age I get an error.
<users>
<user age="42">John Doe</user>
<user age="39">Jane Doe</user>
</users>

You can access the attributes array directly on the node with
MessageBox.Show(node.SelectSingleNode("user").Attributes["age"].InnerText);

Related

Populate ComboBox from XML

I'm trying to populate a Combobox in C# using a field from my XML file, but with no luck... I don't know what is wrong here (it doesn't show anything):
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
XmlDocument doc = new XmlDocument();
doc.Load("Baza_de_cunostinte.xml");
var dataSource = new List<Persoane>();
string PersoanaPlacuta;
foreach (XmlNode node in doc.DocumentElement)
{
string persoanaPlacuta = node["PersoanaPlacuta"].InnerText.Replace("\"", "");
comboBox1.Items.Add(persoanaPlacuta);
}
}
This is the XML file:
<root>
<Persoane>
<Nume>"Bob"</Nume>
<IsMale>true</IsMale>
<Varsta>30</Varsta>
<PersoanaPlacuta>"Iulia"</PersoanaPlacuta>
</Persoane>
<Persoane>
<Nume>"Bogdan"</Nume>
<IsMale>true</IsMale>
<Varsta>28</Varsta>
<PersoanaPlacuta>"Ana"</PersoanaPlacuta>
</Persoane>
</root>
I don't think your are searching in the right Xml node address. You should do it with the full address in order to find the targeted node.
Use XmlNodeList to get all the nodes with the full address and then loop through its items:
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
XmlDocument doc = new XmlDocument();
doc.Load("Baza_de_cunostinte.xml");
var dataSource = new List<Persoane>();
string PersoanaPlacuta;
XmlNodeList xmlNodeList = doc.SelectNodes("//root//Persoane");
foreach (XmlNode node in xmlNodeList)
{
string PersoanaPlacuta = node.ChildNodes[3].InnerText.Replace("\"", "");
comboBox1.Items.Add(PersoanaPlacuta);
}
}
Also you can change the foreach loop like this:
foreach (string PersoanaPlacuta in from XmlNode node in xmlNodeList
select node.ChildNodes[3].InnerText.Replace("\"", ""))
{
comboBox1.Items.Add(PersoanaPlacuta);
}
Note: You better add comboBox1.Items.Clear(); at the first line, otherwise you will get repetitive items in your ComboBox

How to Update XML File in Windows Form

I'm trying to figure out how I can go about updating my XML file. I know how to read and write, but no idea how to update an existing record.
My XML file looks like:
<?xml version="1.0" standalone="yes"?>
<Categories>
<Category>
<CategoryId>1</CategoryId>
<CategoryName>Ayourvedic</CategoryName>
</Category>
<Category>
<CategoryId>2</CategoryId>
<CategoryName>Daily Needs</CategoryName>
</Category>
<Category>
<CategoryId>3</CategoryId>
<CategoryName>Clothes</CategoryName>
</Category>
<Category>
<CategoryId>4</CategoryId>
<CategoryName>Shops</CategoryName>
</Category>
<Category>
<CategoryId>5</CategoryId>
<CategoryName>daily use product</CategoryName>
</Category>
</Categories>
and
This is how I'm writing the file:
private void btnUpdate_Click(object sender, EventArgs e)
{
XmlDocument xdoc = new XmlDocument();
string PATH = "xmldata.xml";
XElement xElement;
xElement = new XElement("Category");
XElement element = new XElement(
"Category",
new XAttribute("CategoryId", CategoryId),
new XAttribute("CategoryName", CategoryName)
);
xElement.Add(element);
xElement.Save("PATH");
}
but my code is not working please any one can give some idea or solution.
Using System.Xml The following code shall help:
static void Main(string[] args)
{
String inputfile = #"D:\Temp\cat.xml";
XmlDocument xmldoc = new XmlDocument();
xmldoc.Load(inputfile);
XmlNode root = xmldoc.DocumentElement;
//Method 1
XmlElement category = xmldoc.CreateElement("Category");
XmlElement catid = xmldoc.CreateElement("CategoryId");
XmlElement catname = xmldoc.CreateElement("CategoryName");
catid.InnerText = "6";
catname.InnerText = "The newly added category";
category.AppendChild(catid);
category.AppendChild(catname);
root.AppendChild(category);
//Method 2
XmlElement category2 = xmldoc.CreateElement("Category");
String catdata = String.Format("<CategoryId>{0}</CategoryId><CategoryName>{1}</CategoryName>", "7", "Adding data by innerXML");
category2.InnerXml = catdata;
root.AppendChild(category2);
xmldoc.Save(inputfile);
}
For further reading refer to XmlDocument and XmlNode
using System.Linq.Xml The following shall help:
static void Main(string[] args)
{
String inputfile = #"D:\Temp\cat.xml";
XDocument xmldoc = XDocument.Load(inputfile);
XElement root = xmldoc.Root;
root.Add(new XElement("Category", new XElement("CategoryId", "8"), new XElement("CategoryName", "Added by LinqXML")));
xmldoc.Save(inputfile);
}
Also you can refer to this answer.
Edit: How to change the value of an element
static void Main(string[] args)
{
String inputfile = #"D:\Temp\cat.xml";
XDocument xmldoc = XDocument.Load(inputfile);
XElement root = xmldoc.Root;
String val = "5";
IEnumerable<XElement> vls = from e in root.Elements("Category") where e.Element("CategoryId").Value.Equals(val) select e;
if (vls.Count() == 1)
{
vls.ElementAt(0).Element("CategoryName").Value = "Value has been changed";
}
xmldoc.Save(inputfile);
}
To further learn refer to this link.

Want to save particular node into the Xml File using c#

code below:
protected void generate_Click(object sender, EventArgs e)
{
XmlDocument doc = new XmlDocument();
doc.PreserveWhitespace = true;
doc.Load("XmlFileName");
XmlNode node = doc.SelectSingleNode("ChartData/XaxisFields/XaxisField");
if (node != null)
{
node.ChildNodes.Item(0).InnerXml = "hi";
doc.Save("XmlFileName");
}
}
Showing null refernce here,
node.ChildNodes.Item(0).InnerXml = "hi";
Is the code is correct,the code behind running not showing any error
but the Xaxisfield is not added.
<?xml version="1.0" encoding="utf-8" ?>
<ChartData>
<XaxisFields>
<XaxisField></XaxisField>
</XaxisFields>
</ChartData>
List item
I want to add the childnode Xaxisfield in the xml file by selcting the particular parent node
You can use Linq to Xml to select your node and update its value:
var xdoc = XDocument.Load("XmlFileName");
xdoc.Root.Element("XaxisFields").Element("XaxisField").Value = "hi";
// OR
// xdoc.XPathSelectElement("//XaxisField").Value = "hi";
xdoc.Save("XmlFileName");
Also your code is not working because there is no child nodes of XaxisField node. This will work:
XmlDocument doc = new XmlDocument();
doc.PreserveWhitespace = true;
doc.Load("XmlFileName");
XmlNode node = doc.SelectSingleNode("ChartData/XaxisFields/XaxisField");
if (node != null)
{
node.InnerXml = "hi";
doc.Save("XmlFileName");
}

writing to xml attributes

Hey all i have code to write to an xml doc from asp
string filePath = Server.MapPath("../XML/MyXmlDoc.xml");
XmlDocument xmlDoc = new XmlDocument();
try
{
xmlDoc.Load(filePath);
}
catch (System.IO.FileNotFoundException)
{
//if file is not found, create a new xml file
XmlTextWriter xmlWriter = new XmlTextWriter(filePath, System.Text.Encoding.UTF8);
xmlWriter.Formatting = Formatting.Indented;
xmlWriter.WriteProcessingInstruction("xml", "version='1.0' encoding='UTF-8'");
string startElement = "markings";
xmlWriter.WriteStartElement(startElement);
xmlWriter.Close();
xmlDoc.Load(filePath);
}
XmlNode root = xmlDoc.DocumentElement;
XmlElement mainNode = xmlDoc.CreateElement("mark");
XmlElement childNode1 = xmlDoc.CreateElement("studentFirstName");
XmlElement childNode2 = xmlDoc.CreateElement("studentLastName");
XmlElement childNode3 = xmlDoc.CreateElement("className");
XmlElement childNode4 = xmlDoc.CreateElement("marks");
XmlText childTextNode1 = xmlDoc.CreateTextNode("");
XmlText childTextNode2 = xmlDoc.CreateTextNode("");
XmlText childTextNode3 = xmlDoc.CreateTextNode("");
XmlText childTextNode4 = xmlDoc.CreateTextNode("");
root.AppendChild(mainNode);
//this portion can be added to a foreach loop if you need to add multiple records
childTextNode1.Value = "John";
childTextNode2.Value = "Doe";
childTextNode3.Value = "Biology";
childTextNode4.Value = "99%";
mainNode.AppendChild(childNode1);
childNode1.AppendChild(childTextNode1);
mainNode.AppendChild(childNode2);
childNode2.AppendChild(childTextNode2);
mainNode.AppendChild(childNode3);
childNode3.AppendChild(childTextNode3);
mainNode.AppendChild(childNode4);
childNode4.AppendChild(childTextNode4);
//end of loop section
xmlDoc.Save(filePath);
which works fine but i want to store the xml in the following structure
graph
set name="John Doe" value="99";
/graph
instead of
name John Doe /name
value 99 /value
is there a way to store the xml like this? thanks all
You can add an attribute to your XmlElement by using the following syntax (C#) :
XmlAttribute value = xmlDoc.CreateAttribute("value");
childNode1.attributes.appendChild(value);
Hope this helps !
This code will do what you're looking for:
XmlElement graph = xmlDoc.CreateElement("graph");
XmlAttribute name = xmlDoc.CreateAttribute("name");
name.Value = "John Doe";
XmlAttribute value = xmlDoc.CreateAttribute("value");
value.Value = "99";
graph.SetAttributeNode(name);
graph.SetAttributeNode(value);
mainNode.AppendChild(graph);

how to determine count of tag

I have a bit of xml file named Sample.xml which is shown below
<?xml version="1.0" encoding="ISO-8859-1"?>
<countries>
<country>
<text>Norway</text>
<value>N</value>
</country>
<country>
<text>Sweden</text>
<value>S</value>
</country>
<country>
<text>France</text>
<value>F</value>
</country>
<country>
<text>Italy</text>
<value>I</value>
</country>
</countries>
i have button named submit(button1).If i click that button i need to display the count(PartitionName="AIX") in a text box named textBox1, means How many PartitionName="AIX" is belonging to Type="NIC"
Can any one give me the c# code
I did like this,,but not able to get the answaer
private void button1_Click(object sender, EventArgs e)
{
XmlDocument doc1 = new XmlDocument();
doc1.Load(#"D:\New Folder\WindowsFormsApplication3\WindowsFormsApplication3\Sample.xml");
XmlNodeList a = doc1.GetElementsByTagName("AIX");
textBox1.Text = a.Count.ToString();
}
here is a quick soln I arrived at using linq. hope you find it useful.
static void Main(string[] args)
{
XElement xElement = XElement.Load(#"C:\Labs\test.xml");
// PartitionName="AIX" is belonging to Type="NIC"
var count = xElement.Descendants().Where(x => x.Name.ToString().Contains("Port")) // namespaces might be used here for faster traversal..
.Where(x => x.HasAttributes && x.Attribute("Type").Value == "NIC")
.Descendants().Where(x => x.Name.ToString().Contains("Client"))
.Where(x => x.Attribute("PartitionName").Value == "AIX").Count();
string str = count.ToString();
Console.WriteLine("Count = {0}", str);
Console.ReadLine();
}
Using xpath something like this:
count(vendor/Slot/Port[#Type='NIC']/Client[#PartitionName='AIX'])
But you have to modify it to support your namespaces.
Also easier and shorter code than going the Linq route for this particular case.
XmlDocument doc = new XmlDocument();
doc.LoadXml(xml);
XmlNamespaceManager nsMgr = new XmlNamespaceManager(doc.NameTable);
nsMgr.AddNamespace("inv", "http://secon.com/Ultravendor");
int count = doc.SelectNodes("inv:vendor/inv:Slot/inv:Port[#Type='NIC']/inv:Client[#PartitionName='AIX']", nsMgr).Count;
XmlDocument doc1 = new XmlDocument();
doc1.Load(#"C:\Labs\test.xml");
XmlNodeList nodes = doc1.GetElementsByTagName("inv:Port");
int count = 0;
foreach (XmlNode childNode in nodes)
{
XmlNodeReader nodeReader = new XmlNodeReader(childNode);
while (nodeReader.Read())
{
if (nodeReader.GetAttribute("PartitionName") == "AIX")
{
count++;
}
}
}
Console.WriteLine("Count = {0}", count);
Console.ReadLine();

Categories

Resources