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

发布于 2024-10-03 09:25:38 字数 524 浏览 4 评论 0原文

我有一个像这样的 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>

我正在使用 LINQ to XML (XDocument) 来读取此文件。我需要的是根元素中的“文本”,“这是子列表的开头”。但是,当我检查引用 Root 的 XElement 的 Value 属性时,我得到以下信息:

这是子列表的开头。ABC这是子列表的结尾。

我做错了什么?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

情魔剑神 2024-10-10 09:25:38

如果您只想要第一个文本节点(忽略“这是子级列表的末尾”,它仍然是根元素中的文本),您可以使用:

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

请注意,这将包含空格,因此您可能需要修剪它。它还假设至少有一个文本节点。

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.

深者入戏 2024-10-10 09:25:38
var doc = XDocument.Parse(xml);
var ele = doc.Element("Root");
string whatUWant = ele.FirstNode.ToString();

这可能会满足您的要求。

顺便说一句,Root.Value 表示节点“Root”的整个值,因此您得到了这样的结果。我猜。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文