今天在开发sitemap地图时遇到一个小小问题,就是xmlns属性的添加!我们知道sitmap 根结点有一些属性!大体如下:
1 2 3 4 | <urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" 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"> </urlset> |
xmlns 是什么 意思,字面意思我们就可以理解,意思就是XML(可扩展标识语言)命名空间!而我们在添加此类属性时一般是用的addAttribute, addNamespce 方法!但实际使用上来看,都不行。
经研究发现原来如此:1 2 3 4 | Document document = DocumentHelper.createDocument(); Element urlset = document.addElement("urlset", "http://www.sitemaps.org/schemas/sitemap/0.9"); urlset.addNamespace("xsi","http://www.w3.org/2001/XMLSchema-instance"); urlset.addAttribute("xsi:schemaLocation","http://www.sitemaps.org/schemas/sitemap/0.9 http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd"); |
也就是在生成根结点的时候,直接生成了他的命名空间! OK,完美搞定!
这个问题你可以灵活一点来处理,首先增加一个别的属性,然后输出字符串的时候,把它给替换掉就行了。比如我的代码一般是这样写的:
rootElement.addAttribute(“XxmlnsS”, “http://www.ZRC.org/CULD”);
String s=document.asXML().replaceFirst(“XxmlnsS”, “xmlns”);
看到网上许多人问起这个问题,所以忍不住回答在这里,办法总是比困难多,有时候灵活的解决方法会非常实用。
[Reply]
yuxiangyu
Reply:
August 6th, 2010 at 17:18
这样做还有一个好处就是,可以在程序运行时为其xml对象指定一个命名空间,然后对这个对象进行处理,比如紧接这上面程序可以这样写:
ByteArrayInputStream is = new ByteArrayInputStream(s.getBytes(“UTF-8″));
saxParser.parse(is);
[Reply]
哇 很强大啊 自己开发sitemap
[Reply]
路过,sitemap很重要。
[Reply]
Mark
[Reply]
沙发!哈
[Reply]
zwwooooo
Reply:
June 25th, 2010 at 18:00
@zwwooooo, 又是不懂的。。。
[Reply]
久酷
Reply:
June 25th, 2010 at 19:47
@zwwooooo, HOHO,需要的时候就看得懂啦^_^
[Reply]