Xelement : more Value in that Value !!

Posted Mon, Jan 5 2009 10:56 by bill

XML is very flexible and somewhat permissive in what it allows. Consider this piece of XML:

      el = <item>some values<first>one</first><second>two</second></item>

 

The element named item can contain both child elements and a text value.  Thankfully this kind of XML is rare: it poses a heap of whitespace formatting issues, and the value itself can reside in any combination of places between the elements, eg:

 

      el = <item>some values<first>one</first> are <second>two</second>in here</item>

 

How this is interpreted is questionable. You could argue that position needs to be preserved, in which case you’d work with the Nodes property, including both the nodes of type XElement and also XText. Each of the inline values, “some values”, “ are ” and “in here”  are actually XText nodes. 

If you’re just after the Text, you need to write a helper function.  If you try to use the Value property you get the Value of all nested nodes.  Calling el.Value with the last example will output:

some valuesone are twoin here

The extension I slapped together is :

   <Extension()> _

   Public Function GetText(ByVal el As XElement) As String

      If Not el.HasElements Then Return el.Value

      Dim sb As New StringBuilder

      For Each nd As XNode In el.Nodes

         If TypeOf nd Is XText Then sb.Append(nd.ToString)

      Next

      Return sb.ToString

   End Function

With this the output is :

some values are in here

Enjoy :)

Filed under: , , , ,