Read XML file ..
I know you will get confuse about my topic. But I am writing this post to give basic function to read an XML file and it returns the value of the given node. Sometimes you will need to store your configuration values in xml file because it is one of the basic methods that we can use to store data.
1. Add these libraries
using System.Xml;
using System.Xml.XPath;
2. This is the function
public static string GetValue(string Element , string FilePath)
{
XPathNavigator nav;
XPathDocument docNav;
XPathNodeIterator NodeIter;
String strExpression;
string value = "";
// Open the XML.
docNav = new XPathDocument(FilePath);
// Create a navigator to query with XPath.
nav = docNav.CreateNavigator();
/// Find the telement of the configure
strExpression = "/Configure/" +Element;
// Select the node and place the results in an iterator.
NodeIter = nav.Select(strExpression);
//Iterate through the results showing the element value.
while (NodeIter.MoveNext())
{
value = NodeIter.Current.Value.ToString().Trim();
};
return (value);
}
}
3. We call this function
string filepath = @"C:\Users\Hasitha\books1.xml";
string element = "Path";
Console.WriteLine(GetValue(element ,filepath));
4. This my xml file
<?xml version='1.0'?>
<!-- This file represents a sample database information -->
<Configure>
<Path>c:\temp</Path>
<Server>SQL SERVER</Server>
</Configure>
5. You can add your own node into xml file then you can modify the strExpression variable
More about XML , XML Path
I know you will get confuse about my topic. But I am writing this post to give basic function to read an XML file and it returns the value of the given node. Sometimes you will need to store your configuration values in xml file because it is one of the basic methods that we can use to store data.
1. Add these libraries
using System.Xml;
using System.Xml.XPath;
2. This is the function
public static string GetValue(string Element , string FilePath)
{
XPathNavigator nav;
XPathDocument docNav;
XPathNodeIterator NodeIter;
String strExpression;
string value = "";
// Open the XML.
docNav = new XPathDocument(FilePath);
// Create a navigator to query with XPath.
nav = docNav.CreateNavigator();
/// Find the telement of the configure
strExpression = "/Configure/" +Element;
// Select the node and place the results in an iterator.
NodeIter = nav.Select(strExpression);
//Iterate through the results showing the element value.
while (NodeIter.MoveNext())
{
value = NodeIter.Current.Value.ToString().Trim();
};
return (value);
}
}
3. We call this function
string filepath = @"C:\Users\Hasitha\books1.xml";
string element = "Path";
Console.WriteLine(GetValue(element ,filepath));
4. This my xml file
<?xml version='1.0'?>
<!-- This file represents a sample database information -->
<Configure>
<Path>c:\temp</Path>
<Server>SQL SERVER</Server>
</Configure>
5. You can add your own node into xml file then you can modify the strExpression variable
More about XML , XML Path
No comments:
Post a Comment