开发者

Using LINQ to XML to read text from XML file

开发者 https://www.devze.com 2023-01-25 17:53 出处:网络
I have an XML file like this: <Root> This is beginning of list of children. <Children> <Child Name=\"a\">A</Child>

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 r开发者_运维知识库ead 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?


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消