【问题标题】:Add namespaces with and without names to an XElement将带名称和不带名称的命名空间添加到 XElement
【发布时间】:2010-06-09 07:52:55
【问题描述】:

我需要生成如下的 XML:

<?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>

我似乎无法弄清楚如何添加没有名称的命名空间而不在所有 url 标记中添加 'xmlns=""'。

我的代码:

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

有什么想法吗?谢谢

【问题讨论】:

    标签: c# xml linq linq-to-xml


    【解决方案1】:

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

            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.Add(您在 urlset XElement 上调用 Add)。这将假设您更改上述代码以首先创建嵌套元素,然后将它们添加到父元素。上面我用了最简洁的写法,就是把所有东西都粘到一个构造函数调用中。或者,如果您有一个 URL 集合,您可以简单地执行上面的 myurls.Select(url => new XElement("url", ...)) ,它将为您集合中的每个 URL 添加一个新的 XElement。
    猜你喜欢
    • 2015-07-20
    • 1970-01-01
    • 2010-09-25
    • 1970-01-01
    • 2023-03-11
    • 1970-01-01
    • 2016-06-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多