2010-06-09 70 views
5

我需要这么生成XML这样的:有和没有名字加入命名空间到的XElement

<?xml version="1.0" encoding="UTF-8" standalone="yes"?> 
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> 
    <url> 
     <loc>http://www.xyz.eu/</loc> 
     <lastmod>2010-01-20T10:56:47Z</lastmod> 
     <changefreq>daily</changefreq> 
     <priority>1</priority> 
    </url> 
    <url> 
     <loc>http://www.xyz.eu/2/</loc> 
     <lastmod>2009-10-13T10:20:03Z</lastmod> 
     <changefreq>daily</changefreq> 
     <priority>0.5</priority> 
    </url> 
    <url> 
     <loc>http://www.xyz.eu/3/</loc> 
     <lastmod>2009-10-13T10:19:09Z</lastmod> 
     <changefreq>daily</changefreq> 
     <priority>0.5</priority> 
    </url> 
</urlset> 

我似乎无法弄清楚如何在不添加名称的命名空间不把“的xmlns =‘’”在所有的url标签中。

我的代码:

XNamespace blank = XNamespace.Get(@"http://www.sitemaps.org/schemas/sitemap/0.9"); 
XNamespace xsi = XNamespace.Get(@"http://www.w3.org/2001/XMLSchema-instance"); 

XDocument doc = new XDocument(
    new XDeclaration("1.0", "utf-8", "yes"), 
    new XElement(blank + "urlset", 
     //new XAttribute(XNamespace.Xmlns +"", blank), 
     new XAttribute(XNamespace.Xmlns + "xsi", xsi), 
     // This private method loops through the dictionary and creates all the page nodes 

     GetSiteMapChildren(pageIdVersionDic, site.Url)    
    )); 

任何想法?谢谢

回答

11

您需要声明“空白”命名空间作为默认命名空间。例如,这工作得很好:

 XNamespace blank = XNamespace.Get(@"http://www.sitemaps.org/schemas/sitemap/0.9"); 
     XNamespace xsi = XNamespace.Get(@"http://www.w3.org/2001/XMLSchema-instance"); 

     XDocument doc = new XDocument(
      new XDeclaration("1.0", "utf-8", "yes"), 
      new XElement(blank + "urlset", 
       new XAttribute("xmlns", blank.NamespaceName), 
       new XAttribute(XNamespace.Xmlns + "xsi", xsi.NamespaceName), 

       new XElement(blank + "url", 
        new XElement(blank + "loc", "http://www.xyz.eu/"), 
        new XElement(blank + "lastmod", "2010-01-20T10:56:47Z"), 
        new XElement(blank + "changefreq", "daily"), 
        new XElement(blank + "priority", "1")) 
      )); 

     Console.WriteLine(doc.ToString()); 
+0

你如何循环? – Mithil 2013-03-05 22:43:00

+0

对不起 - 我不明白你的意思... – 2013-03-06 10:40:09

+0

你的例子只增加一个 .....。我如何添加多个? – Mithil 2013-03-07 16:49:31