Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add namespaces with and without names to an XElement

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>

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

my code:

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

Any ideas? Thanks

like image 200
HarveySaayman Avatar asked Jun 09 '10 07:06

HarveySaayman


People also ask

How do I add a namespace to an XML file?

XML Namespaces - The xmlns Attribute When using prefixes in XML, a namespace for the prefix must be defined. The namespace can be defined by an xmlns attribute in the start tag of an element. The namespace declaration has the following syntax. xmlns:prefix="URI".


1 Answers

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());
like image 82
Vitek Karas MSFT Avatar answered Oct 20 '22 09:10

Vitek Karas MSFT