将具有名称和不具有名称的名称空间添加到XElement [英] Add namespaces with and without names to an XElement

查看:131
本文介绍了将具有名称和不具有名称的名称空间添加到XElement的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要这样生成XML,如下所示:

I need so generate XML like the following:

<?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标记的情况下添加不带名称的命名空间.

I cant seem to figure out how to add the namespace with no name without putting ' xmlns="" ' in all the url tags.

我的代码:

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)             
     ));

有什么想法吗?谢谢

推荐答案

您需要将空白"命名空间声明为默认命名空间.例如,这很好用:

You need to declare the "blank" namespace as the default namespace. For example this works just fine:

        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());

这篇关于将具有名称和不具有名称的名称空间添加到XElement的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆