How to insert some XML into XDocument using Visual Basic?

I am 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 is the image because Qaru does not color well the VB code)

Visual Basic inline XML

... causes this error:

This operation will create an incorrectly structured document.

I don’t know where to add this content.

How do I say to insert this XML bit in <urlset>?

+3
source share
2 answers

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

map.Root.Add(...)
+5
source

Why not completely fill it 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>
+5
source

Source: https://habr.com/ru/post/1707452/


All Articles