Reading value from XML - c#

I am new to C# asp.net coding so I am facing a bit problem.
This is my xml file. I want to retrieve " < DOB > " values of each employee and want to store them in a list, say "emps_dob". Please help me with this. Thank u
<?xml version="1.0" encoding="utf-8"?>
<employees>
<employee>
<name> Vin </name>
<DOB> 07/10 </DOB>
<emailID> vinay#abc.com</emailID>
</employee>
<employee>
<name> ben </name>
<DOB> 08/11 </DOB>
<emailID> ben#abc.com</emailID>
</employee>
<employee>
<name> tin </name>
<DOB> 09/12 </DOB>
<emailID> tin#abc.com</emailID>
</employee>

You can use linq as per answer given in this post
var doc = XDocument.Load("yourfilepath")
var dobs= doc.Root.Elements().Select( x => x.Element("DOB") );
OR
using System;
using System.Xml.Linq;
namespace ConsoleApplication1
{
class Program
{
static void Main( string[] args )
{
XDocument doc = XDocument.Load( "XMLFile1.xml" );
List<string> emps_dob=new List<string>();
var dobs= doc.Descendants( "DOB" );
foreach ( var item in dobs)
{
emps_dob.Add(item.Value);
}
}
}
}

XmlDocument xml = new XmlDocument();
xml.LoadXml(myXmlString);
XmlNodeList xnList = xml.SelectNodes("/employees/employee");
foreach (XmlNode xn in xnList)
{
string name= xn["name"].InnerText;
string DOB= xn["name"].InnerText;
Console.WriteLine("Name: {0} {1}", name, DOB);
}

using System.Xml;
List<string> dob = new List<string>();
XmlDocument doc = new XmlDocument();
doc.Load("abc.xml");
XmlNode root = doc.DocumentElement;
foreach (XmlNode node1 in root.ChildNodes)
{
foreach (XmlNode node2 in node1.ChildNodes)
{
if (node2.Name.ToString() == "DOB")
dob.Add(node2.InnerText.ToString());
}
}

Related

Why is XPathNodeIterator not finding desired path?

I am having a problem with XPathNodeIterator grabbing the data from the given path. When debugging, pNav has all the values from the xml file. However iterator shows a count of 0. It never enters the while loop. Any help would be appreciated.
C#
XPathDocument pdoc = new XPathDocument("Courses.xml");
XPathNavigator pNav = pdoc.CreateNavigator();
XPathNodeIterator iterator = pNav.Select("/Courses/Course");
while (iterator.MoveNext())
{
XPathNodeIterator it = iterator.Current.Select("Name");
it.MoveNext();
string courseName = it.Current.Value;
it = iterator.Current.Select("Code");
it.MoveNext();
string courseCode = it.Current.Value;
Console.WriteLine("{0} {1}", courseName, courseCode);
}
XML:
<Courses xmlns="http://xml" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="Courses.xsd">
<Course>
<Code Undergrad="240"/>
<Name>Biology</Name>
<Instructor>
<Name>
<First>John</First>
<Last>Doe</Last>
</Name>
<Contact>
<Phone>898-989-8989</Phone>
</Contact>
</Instructor>
<Room>515</Room>
</Course>
</Courses>
I expect the output to be
Name = Biology, Code = 240
Because you have
xmlns="http://xml"
in your XML file you need to add a XmlNamespaceManager to allow the navigator to find the nodes. If you remove the xmlns="http://xml" from your XML then you won't need to use an XmlNamespaceManager.
Also the Select method returns a collection of nodes - you need to call SelectSingleNode to get the node you want. E.G.
XPathDocument pdoc = new XPathDocument("Courses.xml");
XPathNavigator pNav = pdoc.CreateNavigator();
var manager = new XmlNamespaceManager(pNav.NameTable);
manager.AddNamespace("cs", "http://xml");
XPathNodeIterator iterator = pNav.Select("/cs:Courses/cs:Course", manager);
while(iterator.MoveNext())
{
var nameNode = iterator.Current.SelectSingleNode("cs:Name", manager);
string courseName = nameNode.Value;
var codeNode = iterator.Current.SelectSingleNode("cs:Code", manager);
codeNode.MoveToFirstAttribute();
string courseCode = codeNode.Value;
Console.WriteLine("{0} {1}", courseName, courseCode);
}
When you get to the Code element, you need to move to the first attribute to get the value, otherwise Value property will return an empty string
It needs to pass namespace resolver to Select-method:
const string xml = #"
<Courses xmlns=""http://xml"" xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"" xsi:schemaLocation=""Courses.xsd"">
<Course>
<Code Undergrad=""240""/>
<Name>Biology</Name>
<Instructor>
<Name>
<First>John</First>
<Last>Doe</Last>
</Name>
<Contact>
<Phone>898-989-8989</Phone>
</Contact>
</Instructor>
<Room>515</Room>
</Course>
<Course>
<Code Undergrad=""000""/>
<Name>Math</Name>
<Instructor>
<Name>
<First>John</First>
<Last>Doe</Last>
</Name>
<Contact>
<Phone>898-989-8989</Phone>
</Contact>
</Instructor>
<Room>515</Room>
</Course>
</Courses>";
using (var stream = new MemoryStream(Encoding.ASCII.GetBytes(xml)))
{
var pdoc = new XPathDocument(stream);
var pNav = pdoc.CreateNavigator();
var manager = new XmlNamespaceManager(pNav.NameTable);
manager.AddNamespace("cs", "http://xml");
var iterator = pNav.Select("/cs:Courses/cs:Course", manager);
foreach (XPathNavigator node in iterator)
{
var courseName = node.SelectSingleNode("cs:Name", manager)?.Value;
var courseCode = node.SelectSingleNode("cs:Code", manager)?.GetAttribute("Undergrad", string.Empty);
Console.WriteLine("{0} {1}", courseName, courseCode);
}
}

Can't figure out how to read xml data in Visual Studio C#

I'm not sure how to read out the data from a XML file.
The XML file looks like this:
<?xml version="1.0" encoding="utf-8"?>
<Lijsten>
<Lijst>
<Titel>Discipline</Titel>
<Waardes>Elektro</Waardes>
<Waardes>Mechanisch</Waardes>
<Waardes>Civiel</Waardes>
<Waardes>Proces</Waardes>
</Lijst>
<Lijst>
<Titel>Soort</Titel>
<Waardes>Tekening</Waardes>
<Waardes>Tekst doc</Waardes>
<Waardes>Afbeelding</Waardes>
</Lijst>
<Lijst>
<Titel>Afdruk</Titel>
<Waardes>Landscape</Waardes>
<Waardes>Portrait</Waardes>
</Lijst>
<Lijst>
<Titel>Kleur</Titel>
<Waardes>Kleur</Waardes>
<Waardes>Zwart</Waardes>
</Lijst>
<Lijst>
<Titel>Kader</Titel>
<Waardes>Aanwezig</Waardes>
<Waardes>Niet aanwezig</Waardes>
</Lijst>
</Lijsten>
I'm trying to create a radio-button menu for every "Lijst".
What I've got so far(not much):
XmlTextReader reader = new XmlTextReader("iniFile.xml");
while (reader.Read())
{
while (reader.ReadToFollowing("Lijst"))
{
while (reader.ReadToFollowing("Titel"))
{
}
}
}
If you don't want to read using XElement, you can use XmlDocument and XPath
Take a look at this example, to get all titles:
XmlDocument xdoc = new XmlDocument();
xdoc.Load(#"C:\temp\inifile.xml");
XmlNodeList nodes = xdoc.SelectNodes("//Titel");
foreach (XmlNode node in nodes)
{
Console.WriteLine(node.InnerText);
}
or, to get all Lijst nodes and then iterate through them to get title and warde values
XmlDocument xdoc = new XmlDocument();
xdoc.Load(#"C:\temp\inifile.xml");
XmlNodeList nodes = xdoc.SelectNodes("//Lijst");
foreach (XmlNode node in nodes)
{
Console.WriteLine("this is List with title: " + node["Titel"].InnerText);
Console.WriteLine("it contains wardes: " + node["Titel"].InnerText);
XmlNodeList wardeNodes = node.SelectNodes("Waardes");
foreach (XmlNode wNode in wardeNodes)
{
Console.WriteLine(" - " + wNode.InnerText);
}
}
With XElement class and LinqToXML:
XElement xml = XElement.Parse(xml);
var buttons = xml.Element("Lijsten")
.Elements()
.Select(p => new { Titel = p.Element("Titel").Value })
.ToArray();

How to get all attribute names from selected XML node in C#

This is my XML file. I need to select one test element and get all attributes name from its result child nodes.
<?xml version="1.0" encoding="UTF-8"?>
<summary>
<test>
<id>test 1</id>
<result value="-45">330</result>
<result value="0">300</result>
<result value="45">340</result>
</test>
<test>
<id>test 3</id>
<result value="-45">330</result>
<result value="0">300</result>
<result value="45">340</result>
</test>
</summary>
I wrote below code. but repeat same values and I want to stop it.
XmlDocument xd = new XmlDocument();
xd.Load(_xmlFilePath);
XmlNodeList nodelist = xd.GetElementsByTagName("result");
foreach (XmlNode node in nodelist)
{
string attrVal = node.Attributes["value"].Value;
Console.WriteLine(attrVal);
}
Any suggestion is appreciated.
Thanks.
You can use LINQ to Xml with XDocument class
var doc = XDocument.Load(_xmlFilePath);
var distinctResults = doc.Descendants("result")
.Select(element => element.Attribute("value").Value)
.Distinct();
foreach(var result in distinctResults)
{
Console.WriteLine(result);
}
Or with using of HashSet<string>
var results = doc.Descendants("result")
.Select(element => element.Attribute("value").Value);
var distinctResults = new HashSet<string>(results);
foreach(var result in distinctResults)
{
Console.WriteLine(result);
}
Try following :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;
namespace ConsoleApplication34
{
class Program
{
const string FILENAME = #"c:\temp\test.xml";
static void Main(string[] args)
{
XDocument doc = XDocument.Load(FILENAME);
string id = "test 1";
var results = doc.Descendants("test").Where(x => (string)x.Element("id") == id).FirstOrDefault().Elements("result").Select(x => new
{
angle = (int)x.Attribute("value"),
length = (int)x
}).ToList();
}
}
}

Query for unique id with XDocument

I have the following XML name Sample.xml which I am trying to query uniqueID with XDocument:
<Request>
<Person xmlns="http://CompanyName.AppName.version1" uniqueID="3221">
<AccountNo>83838</AccountNo>
<FirstName>Tom</FirstName>
<LastName>Jackson</LastName>
</Person>
<Person xmlns="http://CompanyName.AppName.version1" uniqueID="21132">
<AccountNo>789875</AccountNo>
<FirstName>Chris</FirstName>
<LastName>Smith</LastName>
</Person>
</Request>
How do i write code to extract uniqueID of all persons.
You can use LINQ to XML to retrieve the unique ID from your XML document.
string xml = "<Request><Person xmlns='http://CompanyName.AppName.version1' uniqueID='3221'><AccountNo>83838</AccountNo><FirstName>Tom</FirstName><LastName>Jackson</LastName></Person><Person xmlns='http://CompanyName.AppName.version1' uniqueID='21132'><AccountNo>789875</AccountNo><FirstName>Chris</FirstName><LastName>Smith</LastName></Person></Request>";
XDocument doc = XDocument.Parse(xml);
XNamespace ns = "http://CompanyName.AppName.version1";
var uniqueIDs = doc.Descendants(ns + "Person")
.Select(p => p.Attribute("uniqueID").Value)
.ToList();
Try below code With XmlDocument in place
string xml = "<Request><Person xmlns='http://CompanyName.AppName.version1' uniqueID='3221'><AccountNo>83838</AccountNo><FirstName>Tom</FirstName><LastName>Jackson</LastName></Person><Person xmlns='http://CompanyName.AppName.version1' uniqueID='21132'><AccountNo>789875</AccountNo><FirstName>Chris</FirstName><LastName>Smith</LastName></Person></Request>";
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.LoadXml(xml);
XmlNodeList nodeList = xmlDoc.GetElementsByTagName("Person");
foreach (XmlNode node in nodeList)
{
Console.WriteLine(node.Attributes["uniqueID"].Value);
}
You can get the Unique ID by:
string xml="Your XML String";
XmlTextReader reader = new XmlTextReader(new System.IO.StringReader(xml));
XmlDocument doc = new XmlDocument();
XmlNode node = doc.ReadNode(reader);
foreach (XmlNode chldNode in node.ChildNodes)
{
if (chldNode.HasChildNodes)
{
foreach (XmlNode item in node.ChildNodes)
{
string uniqueID = chldNode.Attributes["uniqueID"].Value;
Response.Write(employeeName + "<br />");
}
}
}

Add attributes using XAttribute

I have a root XML which is like this:
<Root xmlns="http://schemas.datacontract.org/2004/07/" xmlns:t="http://www.w3.org/2001/XMLSchema-instance">
<Element1>somevalue</Element1>
<Data/>
<Root>
I need to add few customer related informaiton like (Name, Age etc) under Data Element Node. So, the result I expect is follows:
<Root xmlns="http://schemas.datacontract.org/2004/07/" xmlns:t="http://www.w3.org/2001/XMLSchema-instance">
<Element1>somevalue</Element1>
<Data>
<Name t:type="xs:string" xmlns="" xmlns:s="http://www.w3.org/2001/XMLSchema">Elvis</Name>
<Address t:type="xs:string" xmlns="" xmlns:s="http://www.w3.org/2001/XMLSchema">Some address</Address>
</Data>
<Root>
How can I achieve this? I am using C#, .net 4.0.
I was trying out the below code, but didn't get the result I was expecting:
string strTemplate = "<Root xmlns='http://schemas.datacontract.org/2004/07/' xmlns:t='http://www.w3.org/2001/XMLSchema-instance'><Element1>somevalue</Element1><Data/></Root>";
XDocument doc = XDocument.Parse(strTemplate);
XElement rootElement = doc.Root;
XElement dataElement = null;
foreach (XElement descendant in rootElement.Descendants())
{
if (descendant.Name.LocalName == "Data")
{
dataElement = descendant;
break;
}
}
string cusData = "<CustData><Name>Elvis</Name><Address>XYZ</Address></CustData>";
XElement customerElements = XElement.Parse(cusData);
if (dataElement != null)
{
foreach (XElement custAttributes in customerElements.Descendants())
{
XNamespace t = "http://www.w3.org/2001/XMLSchema-instance";
var attribute = new XAttribute(t + "type", "xs:string");
var attribute1 = new XAttribute(XNamespace.Xmlns + "s", "http://www.w3.org/2001/XMLSchema");
XElement element = new XElement(custAttributes.Name, attribute, attribute1);
element.Value = custAttributes.Value;
dataElement.Add(element);
}
}
string strPayload = doc.ToString();
When I execute the code I get the following:
<Data xmlns="http://schemas.datacontract.org/2004/07/">
<Name t:type="xs:string" xmlns:t="http://www.w3.org/2001/XMLSchema-instance" xmlns="">Elvis</Name>
<Address t:type="xs:string" xmlns:t="http://www.w3.org/2001/XMLSchema-instance" xmlns="">XYZ</Address>
</Data>
Any help appreciated!
Thanks,
M

Categories

Resources