15

I'm getting this error

The prefix '' cannot be redefined from '' to 'http://www.sitemaps.org/schemas/sitemap/0.9' within the same start element tag

while running this code

Dim writer As XmlWriter = XmlWriter.Create(FileLocation + "StaticUrls3.xml")
Dim urlList As New List(Of String)

urlList.Add("link1")
urlList.Add("link2")
urlList.Add("link3")       

writer.WriteStartDocument()
writer.WriteStartElement("urlset")
writer.WriteAttributeString("xmlns", "http://www.sitemaps.org/schemas/sitemap/0.9")

For Each aUrl As String In urlList
    writer.WriteStartElement("url")
    writer.WriteElementString("loc", aUrl)
    writer.WriteEndElement()
Next

writer.WriteEndElement()
writer.WriteEndDocument()
writer.Close()

Why am I getting this error?

1
  • 1
    In XML, QNames are tuples (local name, prefix, namespace URI). So you shouldn't output this element (urlset, '', '') and after that output a default namespace declaration. It's your element under no namespace or under some namespace?
    – user357812
    Sep 27, 2010 at 17:18

1 Answer 1

18

Try this:

Const siteMapNamespace As String = "http://www.sitemaps.org/schemas/sitemap/0.9"
Dim writer As XmlWriter = XmlWriter.Create(FileLocation + "StaticUrls3.xml")
Dim urlList As New List(Of String)

urlList.Add("link1")
urlList.Add("link2")
urlList.Add("link3")       

writer.WriteStartDocument()
writer.WriteStartElement("urlset", siteMapNamespace)

For Each aUrl As String In urlList
    writer.WriteStartElement("url", siteMapNamespace)
    writer.WriteElementString("loc", aUrl)
    writer.WriteEndElement()
Next

writer.WriteEndElement()
writer.WriteEndDocument()
writer.Close()
3
  • 9
    So essentially, if you want to set the xmlns attribute of an element, do it via the second argument of WriteStartElement instead of WriteAttributeString.
    – cdmckay
    Jun 21, 2012 at 14:46
  • 1
    Short answer yes. But what is really going on is that you are specifying a namespace for all your elements. And if you used a different namespace for different elements, I think you would get different xmlns declarations.
    – Markis
    Jun 21, 2012 at 21:56
  • Same probleme for me. How can I define an "xmlns"-attribute and an "xmlns:r"-attribute for the same element?
    – Carsten
    Aug 19, 2020 at 7:31

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.