tags:

views:

98

answers:

4

Hello

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.

+3  A: 

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.

Shaun
+1  A: 

Is Id an attribute on the Url element?

<Pages>
    <Page><Url Id="6428">http://www.example.com/&lt;/Url&gt;&lt;/Page&gt;
</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.)

dtb
A: 

I mabye tirred today,the problem was that in the xml file the attribute was calld "id" and not "Id".

Frozzare
You should put this as and "EDIT:" in your original question rather than a new answer.
Callum Rogers
A: 

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.