How to generate xsi:schemalocation attribute correctly when generating a dynamic sitemap.xml with LINQ to XML?

坚强是说给别人听的谎言 提交于 2019-12-03 08:45:14

Ok, I got it right. Thanks to Mike Caron
If I declare the XAtrribute(XNamespace.Xmlns + "xsi",...) then it works

XNamespace ns = "http://www.sitemaps.org/schemas/sitemap/0.9"; 
XNamespace xsi = "http://www.w3.org/2001/XMLSchema-instance"; 
return new XElement(ns + "urlset",  
    new XAttribute("xmlns", "http://www.sitemaps.org/schemas/sitemap/0.9"),
    new XAttribute(XNamespace.Xmlns + "xsi", "http://www.w3.org/2001/XMLSchema-instance"),
    new XAttribute(xsi + "schemaLocation", "http://www.sitemaps.org/schemas/sitemap/0.9 http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd"),
    from node in GetNodes() 
    select new XElement(ns + "url", 
        new XElement(ns + "loc", node.Loc), 
        new XElement(ns + "lastmod", node.LastMod), 
        new XElement(ns + "priority", node.Priority) 
    ) 
).ToString(); 

I don't know LINQ to XML, but after a quick peek at the documentation, try this:

XNamespace ns = "http://www.sitemaps.org/schemas/sitemap/0.9";
XNamespace xsi = "http://www.w3.org/2001/XMLSchema-instance";
return new XElement(ns + "urlset",
    new XAttribute(xsi + "schemaLocation", "http://www.sitemaps.org/schemas/sitemap/0.9 http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd"),
    from node in new GetNodes()
    select new XElement(ns + "url",
        new XElement(ns + "loc", node.Loc),
        new XElement(ns + "lastmod", node.LastMod),
        new XElement(ns + "priority", node.Priority)
    )
).ToString();

Note that I'm not setting the xmlns attributes explicitly. I suspect they're generated automatically. Also, caveat emptor, since this is not tested.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!