7

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'

Rakesh
  • 2,730
  • 10
  • 39
  • 65

8 Answers8

7

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;

}
Fred
  • 2,402
  • 4
  • 31
  • 58
Pranay Rana
  • 175,020
  • 35
  • 237
  • 263
  • Let's also just note that XmlDocument should become XDocument for the LINQ part. Therefore: XDocument infodoc = XDocument.Load("BackupManager.xml"); – Fred Sep 03 '14 at 22:59
1

In past I had to deal with a huge XML and performance was as issue. All I needed was non-cached, forward-only, read-only access to XML.

Additionally, I did not have had the control over the schema, just had to squeeze out certain tag values, from XML and also CDATA.

Below is what I ended up using :

private string GetValueFromXmlTag(string xml, string tag)
{
    if (xml == null || tag == null || xml.Length == 0 || tag.Length == 0)
        return "";

    string
        startTag = "<" + tag + ">",
        endTag = "</" + tag + ">",
        value = null;

    int
        startTagIndex = xml.IndexOf(tag, StringComparison.OrdinalIgnoreCase),
        endTagIndex = xml.IndexOf(endTag, StringComparison.OrdinalIgnoreCase);


    if (startTagIndex < 0 || endTagIndex < 0)
        return "";

    int valueIndex = startTagIndex += startTag.Length - 1;

    try
    {
        value = xml.Substring(valueIndex, endTagIndex - valueIndex);
    }
    catch (ArgumentOutOfRangeException responseXmlParserEx)
    {
        string err = string.Format("Error reading value for \"{0}\" tag from XXX XML", tag);
        log.Error(err, responseXmlParserEx);
    }

    return (value ?? "");
}
ablaze
  • 722
  • 7
  • 30
1

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;
0

Because you don't have an element with the ID "directory". Either you want

GetElementByID("backUpPath").GetAttribute("value");

Or

GetElementsByTagName("directory");

Remember, that the second method returns a XMLNodeList!

looper
  • 1,929
  • 23
  • 42
0

if you want u can use XmlReader

   string str ="";
   using (var reader = new StreamReader(BackupManager.xml))
            {
                var all = reader.ReadToEnd();
                StringReader stringReader = new StringReader(all);
                XmlReader xmlReader = XmlTextReader.Create(stringReader,new System.Xml.XmlReaderSettings() { IgnoreWhitespace = true, IgnoreComments = true });
                while (xmlReader.Read())
                    if (xmlReader.NodeType == XmlNodeType.Element && xmlReader.Name == "directory")
                         str = xmlReader["value"];

            }
S3ddi9
  • 2,121
  • 2
  • 20
  • 34
0
XmlDocument infodoc = new XmlDocument();
infodoc.Load("BackupManager.xml");
XmlElement directoryElement = document.GetElementById("directory");
string backupPath = directoryElement.GetAttribute("value");
0
if (xml.NodeType == XmlNodeType.Element && xml.Name == "Architecture")
{
    string architecture = xml.ReadElementContentAsString();
}
Elephant
  • 675
  • 1
  • 8
  • 18
0
XmlDocument infodoc = new XmlDocument();
  //Server.MapPath() return the xml file address
            infodoc.Load(Server.MapPath("~/XMLFile1.xml"));
            XmlNodeList nodeList =
(infodoc.SelectNodes("configuration/Settings/backUPpath"));
            foreach (XmlNode elem in nodeList)
            {

               Response.Write(elem.Attributes[1].Value);

            }