SoftwareRockstar
SoftwareRockstar

Reputation: 19

Using LINQ to XML to read text from XML file

I have an XML file like this:

<Root>
   This is beginning of list of children.   
   <Children>
      <Child Name="a">A</Child>
      <Child Name="b">B</Child>
      <Child Name="c">C</Child>
   </Children>
   This is end of list of children. 
</Root>

I am using LINQ to XML (XDocument) to read this file. What I need is the "text" in the root element, "This is beginning of list of children". However when I inspect the Value attribute of the XElement referring to Root, I get the following:

This is begining of list of children.ABCThis is end of list of children.

What am I doing wrong?

Upvotes: 2

Views: 1245

Answers (2)

Jason Li
Jason Li

Reputation: 1585

var doc = XDocument.Parse(xml);
var ele = doc.Element("Root");
string whatUWant = ele.FirstNode.ToString();

This may satisfy your requirement.

BTW, Root.Value means the entire value of the node "Root", so you got the result like that. I Guess.

Upvotes: 2

Jon Skeet
Jon Skeet

Reputation: 1500675

If you just want the first text node (ignoring the "This is the end of list of children" which is still text in the root element), you can use:

var text = (string) doc.Root.Nodes()
                            .OfType<XText>()
                            .First()
                            .Value;

Note that this will contain whitespace, so you may want to trim it. It's also assuming that there is at least one text node.

Upvotes: 2

Related Questions