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>