1

I have the below XML and I load into a XElement in VB.NET and I can get the value of C easily with the below statement but when I try in C#, I get an error with the .Value . How can I access the inner text of C with ease? I can't seem to work out how to access it.

<A>
   <B>
       <C>Message</C>
   </B>
</A>
strMsg = oX.Elements("A").Elements("B").Elements("C").Value
dbc
  • 104,963
  • 20
  • 228
  • 340
MiscellaneousUser
  • 2,915
  • 4
  • 25
  • 44
  • "I get an error with the .Value" - *never* just say "I get an error". *Always* specify the exact error. Now, what do you want to happen if there are multiple elements? Because if you're only expecting a single element, you can just use `Element` instead of `Elements`, and it will be fine. – Jon Skeet Jun 20 '23 at 11:19

2 Answers2

1

The code works in VB due to an extension member in InternalXmlHelper.

The equivalent in C# would be:

string strMsg = oX.Elements("A").Elements("B").Elements("C")
    .FirstOrDefault()?.Value;

Or if you're expecting exactly one of each element in the tree, just use Element instead of Elements:

string strMsg = oX.Element("A").Element("B").Element("C").Value;
Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
1

The XDocument class contains the information necessary for a valid a XML document, which includes an XML declaration. Working directly with XElement is a simpler programming model. You can access your XML value, add XML trees. The Descendants() method returns a collection of the descendant elements for this document or element, in document order.

using System.Xml.Linq;

XDocument xdoc = XDocument.Load(@"..\..\..\test.XML"); // Path Your Xml
var value=xdoc.Descendants("A").Descendants("B").Descendants("C").First().Value;
Jeremy Caney
  • 7,102
  • 69
  • 48
  • 77
Iceberg
  • 21
  • 5