可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
I am generating a dynamic sitemap.xml
According to sitemaps.org this is the header for a sitemap.xml
<?xml version='1.0' encoding='UTF-8'?> <urlset xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.sitemaps.org/schemas/sitemap/0.9 http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd" xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"> <url> ... </url> </urlset>
So I'm using LINQ To XML to generate the sitemap.xml
XNamespace ns = "http://www.sitemaps.org/schemas/sitemap/0.9"; 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 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();
The commented line is the one i cannot get right.
How can i set the "xsi:schemalocation" attribute?
Thanks.
回答1:
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();
回答2:
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.