Tutorial :How do I insert a bit of XML into an XDocument using Visual Basic?



Question:

I'm trying to create a sitemap in an ASP.NET MVC project.

This code in my Node controller...

Function Sitemap() As ContentResult      Dim db As New EfrDotOrgEntities      Dim Nodes = db.Node.ToList      Dim RequestUrl As Uri = Url.RequestContext.HttpContext.Request.Url      Dim AbsoluteRoot As String = String.Format("{0}://{1}", RequestUrl.Scheme, RequestUrl.Authority)        Dim map As XDocument = <?xml version="1.0" encoding="UTF-8"?>                             <urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">                             </urlset>      For Each n As Node In Nodes          map.Add(<url>                      <loc><%= AbsoluteRoot + Url.RouteUrl("IdOnly", New With {.id = n.Id}) %></loc>                  </url>)      Next      Return Content(map.ToString, "text/xml", Encoding.UTF8)  End Function  

(here's an image because Stack Overflow doesn't color VB code well)

Visual Basic inline XML

...produces this error:

This operation would create an incorrectly structured document.

It wouldn't know where to add that content.

How do I tell it to insert that bit of XML into the <urlset>?


Solution:1

You need to add it to the top level element in the document (the root):

map.Root.Add(...)  


Solution:2

Why not fill it out completely with another xml literal hole?

Dim map As XDocument = <?xml version="1.0" encoding="UTF-8"?>                         <urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">                             <%= From n In Nodes.Cast(Of Node)() _                                 Select <url>                                            <loc><%= AbsoluteRoot + Url.RouteUrl("IdOnly", New With {.id = n.Id}) %></loc>                                        </url> %>                         </urlset>  

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »