Peter
Peter

Reputation: 2260

comparing a string from an xml file how?

I am new to this and breaking my head about it, well I got an XML file like :

<?xml version="1.0" encoding="utf-8"?>
<configuration>
<Client>
            <add key="City" value="Amsterdam" />
            <add key="Street" value="CoolSingel" />
            <add key="PostalNr" value="1012AA" />
            <add key="CountryCode" value="NL" />

I'm trying to read and compare a value from an XML file In such a way that i also wont lock the file, like below :

System.Xml.XmlDocument xmlDoc = new System.Xml.XmlDocument();
FileStream xmlFile = new FileStream("c:\clients.xml",FileMode.Open,FileAccess.Read, FileShare.Read);
xmlDoc.Load(xmlFile);

so far nice, but i'm unable to really read from it

if (xmlDoc.GetElementsByTagName("CountryCode")[0].Attributes[0].Value=="NL") {// do stuff}

as a newbie tried several other things here but it just wont work not sure what i do wrong here, does anyone see it ?

Upvotes: 1

Views: 41

Answers (1)

har07
har07

Reputation: 89295

Your code didn't work because CountryCode is not a tag name, it is attribute value.

Since you're new to this thing, learn newer API XDocument, to replace your approach which using older API XmlDocument. For example :

FileStream xmlFile = new FileStream(@"c:\clients.xml",FileMode.Open,FileAccess.Read, FileShare.Read);
XDocument doc = XDocument.Load(xmlFile);

//get <add> element having specific key attribute value :
var countryCode = doc.Descendants("add")
                     .FirstOrDefault(o => (string)o.Attribute("key") == "CountryCode");
if(countryCode != null)
    //print "NL"
    Console.WriteLine(countryCode.Value);

Upvotes: 1

Related Questions