Reputation: 973
I have the following XML file.
<?xml version="1.0" encoding="utf-8" ?>
<Countries>
<Country>
<Id>101</Id>
<City>Austin</City>
</Country>
<Country>
<Id>102</Id>
<City>Dallas</City>
</Country>
<Country>
<Id>103</Id>
<City>Chicago</City>
</Country>
<Country>
<Id>104</Id>
<City>Aman</City>
</Country>
</Countries>
I am trying to read it from code behind. Here is the code
List<City> cityList = new List<City>();
string url = "/App_Data/Countries.xml";
XmlDocument doc = new XmlDocument();
doc.Load(Server.MapPath(url));
XmlNodeList nodeList = doc.SelectNodes("Country");
foreach (XmlNode node in nodeList)
{
if (node != null)
{
int id = int.Parse(node.Attributes["Country"].Value);
string name = node.Attributes["City"].Value;
City city = new City(id, name);
cityList.Add(city);
}
}
For some reason, the code below
XmlNodeList nodeList = doc.SelectNodes("Country");
returns no nodes at all.
Upvotes: 0
Views: 104
Reputation: 3563
If you are targeting .NET 3.5 or upper, I would consider using XDocument API instead of XmlDocument API (see XDocument or XMLDocument).
For your case, an implementation would look like this:
var cityList = new List<City>();
XDocument xDoc = XDocument.Load(Server.MapPath("/App_Data/Countries.xml"));
foreach (XElement xCountry in xDoc.Root.Elements())
{
int id = int.Parse(xCountry.Element("Id").Value);
string name = xCountry.Element("City").Value;
cityList.Add(new City(id, name));
}
Upvotes: 1
Reputation: 973
Thank you all. Figured it. Here is the updated code. But I think there must be a better way of populating objects than what I did.
List<City> cityList = new List<City>();
string url ="/App_Data/Countries.xml";
XmlDocument doc = new XmlDocument();
doc.Load(Server.MapPath(url));
XmlNodeList nodeList = doc.SelectNodes("//Country");
foreach(XmlNode node in nodeList){
if (node != null)
{
int id = int.Parse(node.ChildNodes.Item(0).InnerText);
string name = node.ChildNodes.Item(1).InnerText;
City city = new City(id,name);
cityList.Add(city);
}
}
Upvotes: 0
Reputation: 14624
According to https://msdn.microsoft.com/en-us/library/hcebdtae(v=vs.110).aspx, here's what SelectNodes
method does
Selects a list of nodes matching the XPath expression.
Since you do it like this
XmlNodeList nodeList = doc.SelectNodes("Country");
You're selecting all <Country>
elements within the current context, which is the root, but the <Country>
elements are actually inside <Countries>
, so that's why you got no nodes at all. Change the syntax above to this
XmlNodeList nodeList = doc.SelectNodes("Countries/Country");
Here's more information about the XPath expression examples: https://msdn.microsoft.com/en-us/library/ms256086%28v=vs.110%29.aspx
Upvotes: 2