Add start element with prefix without namespace

Viewed 2004

Is there any way to use WriteStartElement funtion in XmlWriter like this:

XmlWriter.WriteStartElement("prefix", "name", null);

Error occured: System.ArgumentException: 'Unable to use prefix with empty namespace.'

I do not want to set namespace URI when creating element.
Later on ill add it by WriteAttributeString(), when others attributes will be created.

3 Answers

No, a namespace prefix unbound to a namespace URI is meaningless and not allowed in a namespace-well-formed XML document.

I do not want to set namespace URI when creating element. Later on ill add it by WriteAttributeString(), when others attributes will be created.

A prefix always belongs to a namespace. By defining a non-nullnamespace the xmlns attribute will be automatically created:

writer.WriteStartElement("prefix", "localName", "ns"); // <prefix:localName xmlns:prefix="ns" />

I had the same problem, I was searching for a solution, eventually, I realized I should use the same namespace as I defined already.

I had something like this, to create the element:

xmlWriter.WriteStartElement("xhtml", "link", "xmlns");

the result was:

<?xml version="1.0" encoding="utf-8" ?>
<urlset xmlns:xhtml="http://www.w3.org/1999/xhtml" xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
    <url>
        <loc>https://www.my-site.com/en/home</loc>
        <xhtml:link rel="alternative" hreflang="en" href="https://www.my-site.com/en/home" xmlns:xhtml="xmlns" />
        <xhtml:link rel="alternative" hreflang="ar" href="https://www.my-site.com/fr/home" xmlns:xhtml="xmlns" />
        <xhtml:link rel="alternative" hreflang="fa" href="https://www.my-site.com/fa/home" xmlns:xhtml="xmlns" />
    </url>
</urlset>

the problem was the xmlns:xhtml="xmlns" in body of my xhtml:link elements:

<xhtml:link rel="alternative" hreflang="en" href="https://www.my-site.com/en/home" xmlns:xhtml="xmlns" />

so I put the http://www.w3.org/1999/xhtml instead namespace or ns as below:

xmlWriter.WriteStartElement("xhtml", "link", "http://www.w3.org/1999/xhtml");

and now it exactly became what I needed:

<?xml version="1.0" encoding="utf-8" ?>
<urlset xmlns:xhtml="http://www.w3.org/1999/xhtml" xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
    <url>
        <loc>https://www.my-site.com/en/home</loc>
        <xhtml:link rel="alternative" hreflang="en" href="https://www.my-site.com/en/home" />
        <xhtml:link rel="alternative" hreflang="ar" href="https://www.my-site.com/fr/home" />
        <xhtml:link rel="alternative" hreflang="fa" href="https://www.my-site.com/fa/home" />
    </url>
</urlset>
Related