1

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 ?

1 Answer 1

1

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);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.