Showing posts with label xml. Show all posts
Showing posts with label xml. Show all posts

How to Read xml file using Xpath in C#

Hi
Here i will show you how to read the xml file using Xpath in the C#
Here is the XML file which i have used...

< ? xml version="1.0" encoding="UTF-8"?>
< projects>
< project id = "BP001">
< name>Banking Project
< / project>
< project id = "TP001">
< name>Telecommunication Project
< / project>
< project id = "PP001">
< name>Portal Project
< / project>
< / projects>
(please remove the spaces from above XML File)

I have used simple Console Application Which reads this XML File & stores data in the list ...

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.XPath;
using System.Xml;


namespace ConsoleExamples
{
class readXMLusingXPath
{
static void Main(string[] args)
{
readxml read = new readxml();
read.xmlread();
}
}

class readxml
{
private XmlDocument ReadDoc = new XmlDocument();
string nodename = string.Empty;
static XmlNode node;
List strnodes = new List();
public void xmlread()
{
ReadDoc.Load("XMLFile1.xml");
node = ReadDoc.SelectSingleNode("projects");
loadnodes(node);
}
public void loadnodes(XmlNode nd)
{
XmlNodeList nodelist = nd.SelectNodes("project");
foreach (XmlNode node1 in nodelist)
{
if (node1.ToString() != null)
{
strnodes.Add(node1.Name.ToString() + " id = " + node1.Attributes.GetNamedItem("id").Value);
XmlNode node2 = node1.SelectSingleNode("name");
if (node2.ToString() != null)
{
strnodes.Add(node2.Name.ToString() + " = " + node1.SelectSingleNode("name").InnerText);
}
}
}
Console.Read();
}
}
}


Hope it helps ....

How to get data from database into xml ?

It is very easy code....
You just have to use WriteXml() function

here is sample code.........

public DataSet GetLocationByMandate()

{

new SqlConnection("Data Source=.;Initial Catalog=login;Integrated Security=True");

DataSet Ds = new DataSet();

SqlDataAdapter Da = new SqlDataAdapter("your quary",connection);

Da.Fill(Ds);

Ds.WriteXml("locations1.xml");

}


Export xml data into text file

If you want to export attributes from XML file to text file then you just have to read that attribute from xml & write it in text file...I have shown hoe to write string into text file Here ....

Here is full code....Here i have used other way to write string into text file ie. WriteAllText function...

private void button1_Click(object sender, EventArgs e)
{

string text = select();

File.WriteAllText("file.txt", text);

}
public string select()
{
XmlDocument doc = new XmlDocument();
string s = "";
doc.Load("XMLFile1.xml");
XmlNodeList nodes = doc.SelectNodes("/root/row");
foreach (XmlNode node in nodes)
{
XmlAttributeCollection att = node.Attributes;
foreach (XmlAttribute att1 in att)
{
s = s + att1.InnerText + System.Environment.NewLine;

}
}
return s;
}