在 C# 中使用 XElement 获取 XML 的元素节点值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14050507/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 10:31:36  来源:igfitidea点击:

Get Element Node Value of XML using XElement in C#

c#xmlxelement

提问by Siddharth

I have the following XML file saved:

我保存了以下 XML 文件:

<E:Events xmlns:E="Event-Details">
   <Date>12/27/2012</Date>
   <Time>?11:12 PM</Time>
   <Message>Happy Birthday</Message>
</E:Events>

I am using XElementto load the above XML file. I want to get the Element Value of Date, Time and Messagei.e. 12/27/2012, ?11:12 PM and Happy Birthday. How can I retrieve these values. I have searched a lot on this but could not find anything.

我正在使用XElement加载上述 XML 文件。我想获取Date, Time and Messageie 12/27/2012, ?11:12 PM 和的元素值Happy Birthday。如何检索这些值。我对此进行了很多搜索,但找不到任何内容。

Any help appreciated...

任何帮助表示赞赏...

采纳答案by ryadavilli

Have you just tried getting the element from your XElement node?

您是否刚刚尝试从 XElement 节点获取元素?

XElement.Element(" < element name >");

XElement.Element(" <元素名称>");

will return the nodes you need.

将返回您需要的节点。

Try the code below:

试试下面的代码:

string text = "<E:Events xmlns:E=\"Event-Details\"><Date>12/27/2012</Date><Time>?11:12 PM</Time><Message>Happy Birthday</Message></E:Events>";
XElement myEle = XElement.Parse(text);
Console.WriteLine(myEle.Element("Date").Value);
Console.WriteLine(myEle.Element("Time").Value);
Console.WriteLine(myEle.Element("Message").Value);