C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Tip: Please place this file in a convenient location, like a "programs" folder on your C disk volume.
File: sitemap.xml
<?xml version="1.0" encoding="UTF-8"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"
xmlns:image="http://www.google.com/schemas/sitemap-image/1.1">
<url><loc>http://www.dotnetCodex.com</loc></url>
<url><loc>http://www.dotnetCodex.com/24-hour-time</loc></url>
<url><loc>http://www.dotnetCodex.com/2d-array</loc></url>
</urlset>
Elements: We call Elements() in the iteration statement of our ForEach loop. This returns an IEnumerable of XElements.
Element: We use Element() to get the loc element, which is nested with the url element.
Count: We invoke the Count() extension method from LINQ to count all the url elements in the XML file.
LINQVB.NET program that uses XElement, Load
Module Module1
Sub Main()
' Load sitemap XML file from local file.
Dim sitemap As XElement = XElement.Load("C:\\programs\\sitemap.xml")
Dim url As XName = XName.Get("url",
"http://www.sitemaps.org/schemas/sitemap/0.9")
Dim loc As XName = XName.Get("loc",
"http://www.sitemaps.org/schemas/sitemap/0.9")
' Use Elements to loop over XElements.
For Each urlElement As XElement In sitemap.Elements(url)
' Get subelement from URL.
' ... This is a LOC.
Dim locElement As XElement = urlElement.Element(loc)
Console.WriteLine(locElement.Value)
Next
' Count elements.
Console.WriteLine("Count: {0}", sitemap.Elements(url).Count())
End Sub
End Module
Output
http://www.dotnetCodex.com
http://www.dotnetCodex.com/24-hour-time
http://www.dotnetCodex.com/2d-array
Count: 3
Tip: In the above example, the Count() extension acts upon IEnumerable. And For Each requires an IEnumerable interface.
IEnumerableFor Each, ForHowever: Code that uses XElement is clear. It is easy to validate and it will work correctly.
So: In programs that do not require extreme performance, XElement is a good choice. It is a reliable option.