Reputation:
i have a coode that are trying to get the id of xml file where url exist.
My code
public static string GetPageIdByUrl(string url)
{
string folder = HttpContext.Current.Server.MapPath("/App_Data/Pages/" + Path.DirectorySeparatorChar);
foreach (string file in Directory.GetFiles(folder, "*.xml", SearchOption.TopDirectoryOnly))
{
var xml = XDocument.Load(file);
var q = from f in xml.Descendants("Page")
where (string)f.Element("Url").Value == url
select (string)f.Attribute("Id").Value;
if (q.Count() != 0)
{
return q.SingleOrDefault();
}
}
return null;
}
I get this error:
Object reference not set to an instance of an object. Line: select f.Attribute("Id").Value;
if "test" exist in a xml file <Url>test</Url>
i want it to return the attribute ID. But that sems only work for the first xml file.
Hope you get the problem.
Upvotes: 1
Views: 245
Reputation:
Have you considered using XPath instead?
It's been a while since I've used the syntax, but the query should look something similar to this:
/Page[Url='THE_STRING']
Using SelectNodes(), you should get a list of nodes that fit to your query, and from whom you could get the attribute's value.
Upvotes: 0
Reputation: 217361
Is Id
an attribute on the Url
element?
<Pages>
<Page><Url Id="6428">http://www.example.com/</Url></Page>
</Pages>
Then you need something like this:
var q = from f in xml.Descendants("Page")
where (string)f.Element("Url") == url
select (string)f.Element("Url").Attribute("Id");
(Note that you can leave out .Value
when using casts as XElement and XAttribute define casts to various base types. This is often a source of unexpected NullReferenceExceptions.)
Upvotes: 1
Reputation:
I mabye tirred today,the problem was that in the xml file the attribute was calld "id" and not "Id".
Upvotes: 0
Reputation: 4018
Try posting some sample XML.
I'm guessing your Url element doesn't have an "Id" (exact spelling) attribute. Therefore the XNode is null and cannot provide a Value.
Upvotes: 3