How can I get an XElement's .InnerText value in Linq to XML?
-
03-07-2019 - |
Question
I'm trying to extract the polygons from placemarks in a KML file. So far so good:
Imports <xmlns:g='http://earth.google.com/kml/2.0'>
Imports System.Xml.Linq
Partial Class Test_ImportPolygons
Inherits System.Web.UI.Page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim Kml As XDocument = XDocument.Load(Server.MapPath("../kmlimport/ga.kml"))
For Each Placemark As XElement In Kml.<g:Document>.<g:Folder>.<g:Placemark>
Dim Name As String = Placemark.<g:name>.Value
...
Next
End Sub
End Class
I'd like to capture the entire <polygon>...</polygon>
block as a string. I tried something like this (where the ... is above):
Dim Polygon as String = Placemark.<g:Polygon>.InnerText
but the XElement object doesn't have an InnerText property, or any equivalent as far as I can tell. How do I grab the raw XML that defines an XElement?
Solution
What I was missing was that Placemark.<g:Polygon>
is a collection of XElements, not a single XElement. This works:
For Each Placemark As XElement In Kml.<g:Document>.<g:Folder>.<g:Placemark>
Dim Name As String = Placemark.<g:name>.Value
Dim PolygonsXml As String = ""
For Each Polygon As XElement In Placemark.<g:Polygon>
PolygonsXml &= Polygon.ToString
Next
Next
XElement.ToString is the equivalent of InnerText, as tbrownell suggested.
OTHER TIPS
Have you tried:
Placemark.ToString()
I missed the Enumeration also. When using .Value it is possible to receive a null exception. Try the equivelent of this instead:
(string)Placemark.<g:name>
Sorry not sure of the VB syntax,,,it has been a while since I have coded in VB.