Reputation: 309
I’m trying to get the values of an xml snippet that is stored in my database but can’t seem to make it work. They are all coming back null... The xml looks like this:
<fields>
<field id="EmployeeID">1002240002</field>
<field id="JobType">Web Manager</field>
<field id="CompanyCode">R6297C</field>
</fields>
My Code, with the string from the database is below.
string xml = "<fields><field id=\"EmployeeID\">1002240002</field><field id=\"JobType\">Web Manager</field><field id=\"CompanyCode\"> R6297C </field></fields>";
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.LoadXml(xml);
var n = xmlDoc.GetElementById("EmployeeID ");
if (n != null)
{
var employeeId = xmlDoc.GetElementById("EmployeeID ").InnerText;
}
Any help on this? I know I am missing something easy here... Thanks!
Upvotes: 2
Views: 840
Reputation: 236228
You can use following XPath query
string xpath = "field[@id='EmployeeID']";
XmlNode fieldNode = xmlDoc.DocumentElement.SelectSingleNode(xpath);
var id = Int32.Parse(fieldNode.InnerText);
Or Linq to Xml
var id = (from f in xdoc.Descendants()
where (string)f.Attribute("id") == "EmployeeID"
select (int)f).Single();
Or with fluent interface
var id = xdoc.Descendants()
.Where(f => (string)f.Attribute("id") == "EmployeeID")
.Select(f => (int)f)
.Single();
BTW xdoc is an instance of XDocument
class:
var xdoc = new XDocument(xml);
Upvotes: 2