Search code examples
c#xmlxmldocumentcss-selectors

XMLDocument Access To Last Child


i'm developing sitemap project and have a problem;

this is my xml file

<?xml version="1.0" encoding="UTF-8"?>
<urlset>
<url ID="1">
<loc>http://www.serkancamur.com/Site/Index/sayfa/Hakkimda</loc>
<changefreq>Daily</changefreq>
<priority>0,9</priority>
</url>
</urlset>

this is my c# code:

int ID = Convert.ToInt32(doc.SelectSingleNode("urlset").LastChild.Attributes["ID"].Value);

this works but look to urlset element attributes:

<?xml version="1.0" encoding="UTF-8"?>
<urlset xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" schemaLocation="http://www.serkancamur.com/sitemap.xsd">
<url ID="1">
<loc>http://www.serkancamur.com/Site/Index/sayfa/Hakkimda</loc>
<changefreq>Daily</changefreq>
<priority>0,9</priority>
</url>
</urlset>

i only added attributes to urlset element,so why this doesn't work?


Solution

  • You need to use XmlNamespaceManager

    Try this

        int id = 0;
        XmlNamespaceManager nsmgr = new XmlNamespaceManager(doc.NameTable);
        nsmgr.AddNamespace("x", "http://www.sitemaps.org/schemas/sitemap/0.9");
        var urlset = doc.SelectSingleNode("//x:urlset", nsmgr);
        id = Convert.ToInt32(urlset.LastChild.Attributes["ID"].Value);
    

    Hope this helps