今天用c#程序生成百度站点地图文件sitemap.xml的时候,创建url节点多了莫名的多了xmlns属性。原来是上级节点有这个属性,而子节点也要指定,不然就会多这个。问题原因:
当父节点具有XMLNS属性时,子节点必须指定XMLNS属性,但是当子节点的XMLNS属性与父节点命名空间相同时,子节点不显示XMLNS属性,上面问题的根本所在就是我们理解上的错误,认为我没有为子节点指定命名空间,就不应该出现此属性,恰恰相反,当我们为其指定与父节点相同的命名空间时,此属性才不会出现。
原始xml文件内容
- <?xml version="1.0" encoding="UTF-8"?>
- <urlset xmlns="http://www./schemas/sitemap/0.9" xmlns:mobile="http://www.baidu.com/schemas/sitemap-mobile/1/">
- <url>
- <loc>http://m./index.html</loc>
- <mobile:mobile type="mobile" />
- <lastmod>2009-12-14</lastmod>
- <changefreq>daily</changefreq>
- <priority>0.8</priority>
- </url>
- </urlset>
添加节点的c#代码
- public static bool AddUrl2(SitemapUrl model)
- {
- XmlDocument doc = new XmlDocument();
- doc.Load(@"c:\test.xml");
- var rootNode = doc.GetElementsByTagName("urlset");
- if (rootNode.Count == 1)
- {
- var loc = doc.CreateElement("loc");
- loc.InnerText = model.loc;
-
- var lastmod = doc.CreateElement("lastmod");
- lastmod.InnerText = model.lastmod;
-
- var changefreq = doc.CreateElement("changefreq");
- changefreq.InnerText = model.changefreq;
-
- var priority = doc.CreateElement("priority");
- priority.InnerText = model.priority;
-
- var url = doc.CreateElement("url");
- url.AppendChild(loc);
- url.AppendChild(lastmod);
- url.AppendChild(changefreq);
- url.AppendChild(priority);
-
- var root = rootNode[0];
- root.AppendChild(url);
- doc.Save(@"c:\test.xml");
- return true;
- }
- else
- return false;
- }
新加的节点
- <url xmlns="">
- <loc>http://www.baidu.com/</loc>
- <lastmod>2014-12-02</lastmod>
- <changefreq>daily</changefreq>
- <priority>1</priority>
- </url>
新节点多了一个xmlns属性,这个属性是表示命名空间的意思
原来是url的父节点urlset有这个属性,在用c#插入xml节点的时候没有传入这个参数,所以要修复这个问题,不想要这个属性就优传入就可以了。调用CreateElement一个重载方法
doc.CreateElement("url", doc.DocumentElement.NamespaceURI);
完整代码:
- public static bool AddUrl(SitemapUrl model)
- {
- XmlDocument doc = new XmlDocument();
- doc.Load(@"c:\test.xml");
- var rootNode = doc.GetElementsByTagName("urlset", doc.DocumentElement.NamespaceURI);
- if (rootNode.Count == 1)
- {
- var loc = doc.CreateElement("loc", doc.DocumentElement.NamespaceURI);
- loc.InnerText = model.loc;
-
- var lastmod = doc.CreateElement("lastmod", doc.DocumentElement.NamespaceURI);
- lastmod.InnerText = model.lastmod;
-
- var changefreq = doc.CreateElement("changefreq", doc.DocumentElement.NamespaceURI);
- changefreq.InnerText = model.changefreq;
-
- var priority = doc.CreateElement("priority", doc.DocumentElement.NamespaceURI);
- priority.InnerText = model.priority;
-
- var url = doc.CreateElement("url", doc.DocumentElement.NamespaceURI);
- url.AppendChild(loc);
- url.AppendChild(lastmod);
- url.AppendChild(changefreq);
- url.AppendChild(priority);
-
- var root = rootNode[0];
- root.AppendChild(url);
- doc.Save(@"c:\test.xml");
- return true;
- }
- else
- return false;
- }
注意:url的子节点(如:loc,lastmod)创建的也得传入doc.DocumentElement.NamespaceURI这个参数,不然也会多了一个xmlns=""。当然从开始就没有指定xmlns,就不用这们传入doc.DocumentElement.NamespaceURI了。
|