简体   繁体   English

使用LINQ to XML从XML文件读取文本

[英]Using LINQ to XML to read text from XML file

I have an XML file like this: 我有一个像这样的XML文件:

<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. 我正在使用LINQ to XML(XDocument)读取此文件。 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: 但是,当我检查XElement的Root的Value属性时,得到以下信息:

This is begining of list of children.ABCThis is end of list of children. 这是孩子列表的开头。ABC这是孩子列表的结尾。

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. 顺便说一句,Root.Value表示节点“ Root”的整个值,因此您得到了这样的结果。 I Guess. 我猜。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM