Read XML file using Xml.Xpath and Xml.Linq



I am trying to read the following XML file:



<?xml version="1.0" encoding="utf-8"?>
<Connection name="default">
<Attribute name="server" value="localhost" />
<Attribute name="database" value="mp" />
<Attribute name="uid" value="root" />
<Attribute name="password" value="m123" />
<Attribute name="code" value="MK" />
</Connection>


With the following code:



var doc = XDocument.Load("DBConnect.xml");
var values = doc.XPathSelectElements("//Connection[@name='default']");
foreach (var item in values)
{
foreach (var att in item.Elements("Attribute"))
{
_server = att.Attribute("server").Value;
_database = att.Attribute("database").Value;
_uid = att.Attribute("uid").Value;
_password = att.Attribute("password").Value;
_code = att.Attribute("code").Value;
}
}


However, I don't seem to be getting the correct output. I am getting an error message which tells me _server is null. Any idea why? I don't think I am correctly referencing the XML attribute values I want to get a hold of.


No comments:

Post a Comment