Asked by:
Changing xml tags how to read in c sharp

Question
-
User-148788041 posted
Hi
Input is an xml.i do not know structure of xml.
How to read each nodes.there is no nested xml tags. How to read and print it.
GuhaWednesday, October 24, 2018 11:39 AM
All replies
-
User2103319870 posted
How to read each nodes.there is no nested xml tagsIf its well formed simple xml file then you can try with DateSet's ReadXml(XmlReader) method to read the data from Xml in to dataset .
string filePath = Server.MapPath("~/XMLFile1.xml"); //Create Dataset to hold the data using (DataSet ds = new DataSet()) { //Read the data into dataset ds.ReadXml(filePath); //loop through dataset and read values foreach (DataTable dt in ds.Tables) { foreach (DataRow row in dt.Rows) { foreach (object item in row.ItemArray) { // read item Console.WriteLine(item); } } } }
Sample XML I used
<?xml version="1.0" encoding="utf-8" ?> <rootnodes> <node> Val1 </node> <node> Val2 </node> <node> Val3 </node> <node> Val4 </node> </rootnodes>
Wednesday, October 24, 2018 1:07 PM -
User-148788041 posted
If there are nodes like this how to read
Name
Age
Sex
How to read.Thursday, October 25, 2018 4:20 AM -
User839733648 posted
Hi Guhananth,
Do you mean that you want to read and print the tags?
I've made a sample and maybe you could refer to.
xml.
<?xml version="1.0" encoding="utf-8" ?> <tags> <name> 1111 </name> <age> 2222 </age> <sex> 3333 </sex> </tags>
XmlDocument xml = new XmlDocument(); xml.Load(@"C:\XMLFile1.xml"); foreach (XmlNode node in xml.DocumentElement.ChildNodes) { Console.WriteLine(node.Name); }
the result is like:
name age sex
Best Regards,
Jenifer
Thursday, October 25, 2018 6:51 AM -
User2103319870 posted
Are you having one rootnode and all values inside it. If possible paste a sample xml structure.
Thursday, October 25, 2018 2:42 PM -
User-148788041 posted
Print the tag and valuesSaturday, October 27, 2018 5:26 AM -
User2103319870 posted
Print the tag and values
To read the value from node, you can use InnerText property of XMLnode like below. I used the sample xml provided in previous post by Jenifer
XmlDocument xml = new XmlDocument(); xml.Load(@"C:\Forums\XMLFile1.xml"); foreach (XmlNode node in xml.DocumentElement.ChildNodes) { Console.WriteLine("Node Name : " + node.Name); Console.WriteLine("Node Value : " + node.InnerText.Trim()); }
Saturday, October 27, 2018 5:44 PM