Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# GET XML TAG VALUE

Tags:

c#

xml

I have an xml file named BackupManager.xml

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<Settings>
<directory id="backUpPath" value="D:/BACKUPS/"></directory>
<filename id="feilname" value="SameName"></filename>
<period id ="period" value="15"></period>
</Settings>
</configuration>

I am trying to get value from the tags to a string Eg:- I need value of 'backUpPath' tag as 'D:/BACKUPS/' to a string say 'str'

The code I have tried is

XmlDocument infodoc = new XmlDocument();
infodoc.Load("BackupManager.xml");
//int col = infodoc.GetElementsByTagName("directory").Count;
String str = infodoc.GetElementByID("directory").value;

But i am getting null value on 'str'

like image 597
Rakesh Avatar asked Nov 28 '12 12:11

Rakesh


2 Answers

try out

linq to xml way

IEnumerable<XElement> direclty = infodoc.Elements("Settings").Elements("directory");
var rosterUserIds = direclty .Select(r => r.Attribute("value").Value);

OR

   XmlNodeList nodeList=
(infodoc.SelectNodes("configuration/Settings/directory"));

foreach (XmlNode elem in nodeList)
{
string strValue = elem.Attributes[1].Value;

}
like image 140
Pranay Rana Avatar answered Sep 25 '22 07:09

Pranay Rana


Use this for short syntax if you want get value of 'directory' tag in this case:

var directory = infodoc.GetElementsByTagName("directory")[0].Attributes["value"].Value;
like image 22
nguyenhoavuong Avatar answered Sep 25 '22 07:09

nguyenhoavuong