Reading the XML file in c# - c#

I have the following XML file (parse.xml):
<Invoice>
<InvoiceHeader>
<Name>cust1</Name>
<Number>5689</Number>
</InvoiceHeader>
<InvoiceHeader>
<Name>cust1</Name>
<Number>5689</Number>
<Number>5459</Number>
</InvoiceHeader>
<InvoiceHeader>
<Name>cust1</Name>
<Number>5689</Number>
<Number>5645</Number>
<Number>5879</Number>
</InvoiceHeader>
</Invoice>
I would like to read it into a list of the following class:
public class Details
{
public string Name {get; set;}
public List<string> Number{get; set;}
}
As you can see, in the XML the node Number can appear more than one time in InvoiceHeader. I'm not sure how to parse this XML into the List<Details> class.
I tried my code:
List<Details> details = new List<Details>;
XmlDocument doc = new XmlDocument();
doc.Load("parse.xml");
XmlNodeList nodeList = doc.SelectNodes("/Invoice/InvoiceHeader");
foreach (XmlNode node in nodeList)
{
details.Add(node["Name"].InnerText);
XmlNodeList dd = node.ChildNodes;
foreach (XmlNode inch in dd)
{
details.Add(node["Number"].InnerText);
}
}
I know this code isn't right but wanted to show what I have done so far.

nodeList is a list of <InvoiceHeader> nodes. One method to solve this problem would be to iterate through the ChildNodes of nodeList and use the property Name to create the Details class in each iteration.
Your code was almost there... I've just updated it slightly so it correctly adds the <Number> elements to the list:
List<Details> detailsList = new List<Details>();
XmlDocument doc = new XmlDocument();
doc.Load(path);
XmlNodeList nodeList = doc.SelectNodes("/Invoice/InvoiceHeader");
foreach (XmlNode node in nodeList)
{
// create details class for each InvoiceHeader
Details detail = new Details();
detail.Number = new List<string>();
// loop over child nodes to get Name and all Number elements
foreach (XmlNode child in node.ChildNodes)
{
// check node name to decide how to handle the values
if (child.Name == "Name")
{
detail.Name = child.InnerText;
}
else if (child.Name == "Number")
{
detail.Number.Add(child.InnerText);
}
}
detailsList.Add(detail);
}
Then you can display the results like this:
foreach (var details in detailsList)
{
Console.WriteLine($"{details.Name}: {string.Join(",", details.Number)}");
}
// output
cust1: 5689
cust1: 5689,5459
cust1: 5689,5645,5879
Another method you could consider is Linq-to-Xml. The below code produces the same output as that above:
XDocument doc = XDocument.Load(path);
var details = doc.Descendants("Invoice")
.Elements()
.Select(node => new Details()
{
Name = node.Element("Name").Value,
Number = node.Elements("Number").Select(child => child.Value).ToList()
})
.ToList();

Please find below code attachment
You need to follow this few steps
using System.Xml;
XmlTextReader reader = new XmlTextReader ("file name.xml");
while (reader.Read())
{
// Do some work here on the data.
Console.WriteLine(reader.Name);
}
Console.ReadLine();
while (reader.Read())
{
switch (reader.NodeType)
{
case XmlNodeType.Element: // The node is an element.
Console.Write("<" + reader.Name);
Console.WriteLine(">");
break;
case XmlNodeType.Text: //Display the text in each element.
Console.WriteLine (reader.Value);
break;
case XmlNodeType. EndElement: //Display the end of the element.
Console.Write("</" + reader.Name);
Console.WriteLine(">");
break;
}
}
while (reader.Read())
{
switch (reader.NodeType)
{
case XmlNodeType.Element: // The node is an element.
Console.Write("<" + reader.Name);
while (reader.MoveToNextAttribute()) // Read the attributes.
Console.Write(" " + reader.Name + "='" + reader.Value + "'");
Console.WriteLine(">");
break;
case XmlNodeType.Text: //Display the text in each element.
Console.WriteLine (reader.Value);
break;
case XmlNodeType. EndElement: //Display the end of the element.
Console.Write("</" + reader.Name);
Console.WriteLine(">");
break;
}
}
finally save code and run them...
Complete code listing
using System;
using System.Xml;
namespace ReadXMLfromFile
{
/// <summary>
/// Summary description for Class1.
/// </summary>
class Class1
{
static void Main(string[] args)
{
XmlTextReader reader = new XmlTextReader ("file name.xml");
while (reader.Read())
{
switch (reader.NodeType)
{
case XmlNodeType.Element: // The node is an element.
Console.Write("<" + reader.Name);
Console.WriteLine(">");
break;
case XmlNodeType.Text: //Display the text in each element.
Console.WriteLine (reader.Value);
break;
case XmlNodeType.EndElement: //Display the end of the element.
Console.Write("</" + reader.Name);
Console.WriteLine(">");
break;
}
}
Console.ReadLine();
}
}
}

Related

Reading XML giving null

<tours xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="http://api.contiki.com/schemas/v2/detailed_tours.xsd">
<tour>
<id>290</id>
<name>Peru Uncovered</name>
<lowest_price>
<code>11D15a</code>
</lowest_price>
</tour>
</tours>
I want to read Id, name and code.
I am trying this code
XmlTextReader reader = new XmlTextReader(downloadfolder);
XmlDocument doc = new XmlDocument();
XmlNode node = doc.ReadNode(reader);
foreach (XmlNode chldNode in node.ChildNodes)
{
string employeeName = chldNode.Attributes["name"].Value;
}
But i am getting null. Can anyone tell me how can i read the values? i can not use Linq as i am working in SSIS 2008 project which does not support linq.
Updated Answer
XmlTextReader reader = new XmlTextReader(downloadfolder);
while (reader.Read())
{
switch (reader.NodeType)
{
case XmlNodeType.Element: // The node is an element.
string node = reader.Name;
if (node == "id")
{
string id = reader.ReadString();
}
if (node == "name")
{
string name = reader.ReadString();
}
if (node == "code")
{
string code = reader.ReadString();
}
break;
}
I can read the values but how can i add these as a row in my data table?
here node type of "name" is element.
below code can be used for node type checking
XmlTextReader reader = new XmlTextReader ("<file name>");
while (reader.Read())
{
switch (reader.NodeType)
{
case XmlNodeType.Element:
Reference : http://support.microsoft.com/en-us/kb/307548

Read XML Webfile in C# Windows Form and place data in labels

For my information program I need to read a web xml file and place it in a label for every value.
An example of the XML file:
<ActueleVertrekTijden>
<VertrekkendeTrein>
<RitNummer>5070</RitNummer>
<VertrekTijd>2015-03-20T19:42:00+0100</VertrekTijd>
<EindBestemming>Den Haag Centraal</EindBestemming>
<TreinSoort>Sprinter</TreinSoort>
<RouteTekst>Lage Zwaluwe, Dordrecht, Rotterdam C.</RouteTekst>
<Vervoerder>NS</Vervoerder>
<VertrekSpoor wijziging="false">6</VertrekSpoor>
</VertrekkendeTrein>
<VertrekkendeTrein>
<RitNummer>1971</RitNummer>
<VertrekTijd>2015-03-20T19:50:00+0100</VertrekTijd>
<EindBestemming>Venlo</EindBestemming>
<TreinSoort>Intercity</TreinSoort>
<RouteTekst>Tilburg, Eindhoven, Helmond</RouteTekst>
<Vervoerder>NS</Vervoerder>
<VertrekSpoor wijziging="false">4</VertrekSpoor>
<Opmerkingen> // This is not always available, but it is important and specific for a 'VertrekkendeTrein'
<Opmerking>Rijdt vandaag niet</Opmerking>
</Opmerkingen>
</VertrekkendeTrein>
</ActueleVertrekTijden>
I tried it with XMLDocument (using foreach) like this:
foreach (XmlNode nodelist2 in nodeList)
{
if (i < 1) //1
{
switch (nodelist.Name)
{
case "VertrekTijd": string vertrek1 = (nodelist2.InnerText); break;
case "VertrekVertragingsTekst": string vertraging1 = (nodelist2.InnerText); break;
case "EindBestemming": string eindbest1 = (nodelist2.InnerText); break;
case "TreinSoort": string treinsoort1 = (nodelist2.InnerText); break;
case "RouteTekst": string route1 = (nodelist2.InnerText); break;
case "VertrekSpoor": string spoor1 = (nodelist2.InnerText); i++ break;
case "Opmerkingen": case "Opmerking": string opmerking1 = (nodelist2.InnerText); break;
}
}
}
But it wasn't a success.
Is there a smarter way to read it, and place it in a lot of labels?
EDIT:
With the answer I got, I tried the following code:
try
{
string urlo = "**secured webaddress that not end with .xml**";
string resultje = HttpGeto(urlo);
XmlDocument doc = new XmlDocument();
XmlNode root = doc.FirstChild;
//* the document has one root element "ActueleVertrekTijden"
//* the root element has multiple child nodes "VertrekkendeTrein"
XmlNodeList nodelist1 = root.ChildNodes;
for (int i = 0; i < nodelist1.Count; i++)
{
XmlNodeList nodelist2 = nodelist1[i].ChildNodes;
//* for each child node get all of all of child nodes,
//* that is where you need to get the text within each one of them
foreach (XmlNode node in nodelist2)
{
switch (node.Name)
{
case "VertrekTijd":
string vertrek1 = node.InnerText; MessageBox.Show(vertrek1); lblts1.Text = vertrek1;
break;
case "VertrekVertragingsTekst":
string vertraging1 = node.InnerText;
break;
case "EindBestemming":
string eindbest1 = node.InnerText;
break;
case "TreinSoort":
string treinsoort1 = node.InnerText;
break;
case "RouteTekst":
string route1 = node.InnerText;
break;
case "VertrekSpoor":
string spoor1 = node.InnerText;
break;
case "Opmerkingen":
XmlNode OpNode = node.FirstChild;
if (OpNode != null)
{
string opmerking1 = OpNode.InnerText;
}
break;
}
}
}
}
catch
{
lblcatch.Text = "werktniet";
}
But it doesn't work. And also, how can i read the next "VertrekkendeTrein"?, just by copying the code and use the I++;? I need to read the first 6 "VertrekkendeTrein".
XmlNode root = doc.FirstChild;
//* the document has one root element "ActueleVertrekTijden"
//* the root element has multiple child nodes "VertrekkendeTrein"
XmlNodeList nodelist1 = root.ChildNodes;
for (int i=0; i<nodelist1.Count; i++)
{
XmlNodeList nodelist2 = nodelist1[i].ChildNodes;
//* for each child node get all of all of child nodes,
//* that is where you need to get the text within each one of them
foreach (XmlNode node in nodeList2)
{
switch (node.Name)
{
case "VertrekTijd":
string vertrek1 = node.InnerText;
break;
case "VertrekVertragingsTekst":
string vertraging1 = node.InnerText;
break;
case "EindBestemming":
string eindbest1 = node.InnerText;
break;
case "TreinSoort":
string treinsoort1 = node.InnerText;
break;
case "RouteTekst":
string route1 = node.InnerText;
break;
case "VertrekSpoor":
string spoor1 = node.InnerText;
break;
case "Opmerkingen":
XmlNode OpNode = node.FirstChild;
if(OpNode!=null)
{
string opmerking1 = OpNode.InnerText;
}
break;
}
}
}

is it possible to detect if an xml node is present using c#?

i have a xml file and i want to know if it is possible to see if the <VertrekVertragingTekst> is present in the xml file.
this is the xml node:
<VertrekkendeTrein>
<RitNummer>4722</RitNummer>
<VertrekTijd>2014-06-03T09:45:00+0200</VertrekTijd>
<VertrekVertraging>PT2M</VertrekVertraging>
<VertrekVertragingTekst>+2 min</VertrekVertragingTekst>
<EindBestemming>Uitgeest</EindBestemming>
<TreinSoort>Sprinter</TreinSoort>
<Vervoerder>NS</Vervoerder>
<VertrekSpoor wijziging="false">2</VertrekSpoor>
</VertrekkendeTrein>
(these nodes are in dutch so dont pay attention to what they say, that is not important)
this is the c# code that i have so far:
XmlNodeList nodeList = xmlDoc.SelectNodes("ActueleVertrekTijden/VertrekkendeTrein/*");
foreach (XmlNode nodelist2 in nodeList)
{
if (i < 1) //1
switch (nodelist2.Name)
{
case "VertrekTijd": string kuttijd1 = (nodelist2.InnerText);
var res1 = Regex.Match(kuttijd1, #"\d{1,2}:\d{1,2}").Value;
lblv1.Text = Convert.ToString(res1); break;
case "VertrekVertragingTekst": ververt1.Text = (nodelist2.InnerText); ververt1.Visible = true; vertpic1.Visible = true; logo1.Top -= 9; lblts1.Top -= 9; break;
case "EindBestemming": string vertrek1 = (nodelist2.InnerText); if (vertrek1 == "Uitgeest") { lblvia1.Text = "Krommenie-Ass"; } lblbs1.Text = vertrek1; break;
case "TreinSoort": lblts1.Text = (nodelist2.InnerText); break;
case "RouteTekst": lblvia1.Text = (nodelist2.InnerText); break;
case "VertrekSpoor": lbls1.Text = (nodelist2.InnerText); i++; break;
}
}
i can read out of this file and everything works but i want to know how i can detect the presence of this node?
Use SelectSingleNode Method
var result = node.SelectSingleNode("nodeTocheck");
if(result!=null)
{
}
It could be done with Linq To Xml based on the following code snippet.
XDocument XmlDoc = XDocument.Parse(Doc);
var Query = XmlDoc.Root.DescendantNodes()
.OfType<XElement>()
.Where(iEl =>iEl.Name.LocalName.Equals("NodeName"));
The sequence would contain all nodes of name NodeName.
I use XmlReader class to read XML files, you can also give it a try
namespace System.Xml.XmlReader
Example:
String xmlString =
#"<bookstore>
<book genre='autobiography' publicationdate='1981-03-22' ISBN='1-861003-11-0'>
<title>The Autobiography of Benjamin Franklin</title>
<author>
<first-name>Benjamin</first-name>
<last-name>Franklin</last-name>
</author>
<price>8.99</price>
</book>
</bookstore>";
// Create an XmlReader
using (XmlReader reader = XmlReader.Create(new StringReader(xmlString)))
{
if(reader.ReadToFollowing("book"))
{
reader.MoveToFirstAttribute();
string genre = reader.Value;
Console.WriteLine("The genre value: " + genre);
}
else
{
//Do something else
}
}
Output
The genre value: autobiography

Treeview C# building Hierarchy WPF

how do i create a hierarchical structure in WPF using treeview?
Here is my suggestion:
//create treeNode myParent = null;
while (Reader.Read())
{
switch (reader.NodeType)
{
case XmlNodeType.Element: // The node is an element.
var newNode = new TreeViewItem
{
Header = reader.Name
};
if(theParent !=null)
{
theParent.Items.Add(newnode);
}
else
{
treeView.Items.Add(newnode);
}
theParent = newnode;
break;
case XmlNodeType.Text: //Display the text in each element.
Console.WriteLine(reader.Value);
break;
case XmlNodeType.EndElement: //Display the end of the element.
Console.Write("</" + reader.Name);
Console.WriteLine(">");
if (theParent != null)
{
theParent = theParent.Parent;
}
break;
}
}
Don't try to manipulate the WPF TreeView directly. Instead, make your own "view model" representing a node, then bind it recursively to the TreeView using HierarchicalDataTemplate.
More info here.

Getting the value of XML tag xith XMLReader and add to LinkedList C#

I am a new to programming, and have a serious problem and cant get out of it.
I have 5 XML URLs. such as http://www.shopandmiles.com/xml/3_119_3.xml
This is an XML URL which I have to get values and write to database in related columns.
My column names and XML tag names do match.
When I write the below code, reader element miss null xml values. Some tags do not have value inside. I have to add them null to linkedlist because after that code, i am going through the linked list but the order doesnt match if ı cant add a value for null xml values. So column names and data inside doesnt match. i lose the order. My all code is here, you can also check comment in the code if that helps. Thank you all.
public void WebServiceShopMilesCampaignsXMLRead(string URL)
{
XmlReader reader = XmlReader.Create(URL);
LinkedList<string> linkedList = new LinkedList<string>();
List<ShopAndMilesCampaigns> shopMileCampaigns = new List<ShopAndMilesCampaigns>();
try
{
while (reader.Read())
{
switch (reader.NodeType)
{
case XmlNodeType.Text:
linkedList.AddLast(reader.Value);
break;
}
}
}
catch (XmlException exception)
{
Console.WriteLine("XML okurken bir sorun oluştu, hata detayı --> " + exception.Message);
}
LinkedListNode<string> node = linkedList.First;
while (node != null)
{
ShopAndMilesCampaigns shopMilesCampaign = new ShopAndMilesCampaigns();
shopMilesCampaign.Name = node.Value; // Null values mixes up the order because i cant add as null with reader.read above
node = node.Next;
shopMilesCampaign.Summary = node.Value;
node = node.Next;
shopMilesCampaign.AccountName = node.Value;
node = node.Next;
shopMilesCampaign.Category = node.Value;
node = node.Next;
shopMilesCampaign.Sector = node.Value;
node = node.Next;
shopMilesCampaign.Details = node.Value;
node = node.Next;
shopMilesCampaign.Image = node.Value;
node = node.Next;
shopMilesCampaign.Status = 1;
node = node.Next;
shopMileCampaigns.Add(shopMilesCampaign);
}
foreach (ShopAndMilesCampaigns shopMileCampaign in shopMileCampaigns)
{
shopMileCampaign.Insert();
}
}
I found the answer. Here it is to let you know.
If the XmlNodeType is equal to Element, then the loop continues to read from the XML data and looks for Whitesapces and end Element of XML tag. The below code gives me the exact value of XML tag even it is empty.
public LinkedList<string> AddToLinkedList(XmlReader reader)
{
LinkedList<string> linkedList = new LinkedList<string>();
try
{
while (reader.Read())
{
switch (reader.NodeType)
{
case XmlNodeType.Element:
reader.Read();
Start:
if (reader.NodeType == XmlNodeType.Whitespace || reader.NodeType == XmlNodeType.Element)
{
reader.Read();
goto Start;
}
else if (reader.NodeType == XmlNodeType.EndElement)
{
linkedList.AddLast("");
}
else
{
linkedList.AddLast(reader.Value);
}
break;
}
}
}

Categories

Resources