使用 LINQ to XML 从 XML 文件读取文本
我有一个像这样的 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果您只想要第一个文本节点(忽略“这是子级列表的末尾”,它仍然是根元素中的文本),您可以使用:
请注意,这将包含空格,因此您可能需要修剪它。它还假设至少有一个文本节点。
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:
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.
这可能会满足您的要求。
顺便说一句,Root.Value 表示节点“Root”的整个值,因此您得到了这样的结果。我猜。
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.