在 C# 中,我如何使用 xml.linq 获取嵌套在 xml 中的值?

In C# how would I use xml.linq to grab values nested in xml?

抱歉,如果有人问过这个问题,我找不到了。 我对 XML 不是很好,但我正在尝试使用它

xml 看起来像这样:

<?xml version="1.0" encoding="utf-8" ?>
<Config>
  <commands>
    <command name="check">
      <stdout>output_value</stdout>
    </command>
    <command name="ping http://192.168.1.1">
      <stdout>result</stdout>
    </command>
    <command name="config">
      <stdout>Initialized</stdout>
      <stdout>listen on http://127.0.0.1:8888</stdout>
      <stdout>loaded</stdout>
      <stdout>verified</stdout>
      <stdout>connected</stdout>
      <stdout>connection INITIALIZED</stdout>
      <stdout>load complete</stdout>
    </command>
    <command name="connection">
      <stdout>Got connection</stdout>
    </command>
  </commands>
</Config>

基本上我试图在每个命令下获取文本在标准输出中的位置。

我发现我可以通过

到达它所说的"name of command"
XDocument xd = XDocument.Load("config.xml");
var commandcheck = from paths in xd.Decendants(xmln)
                   select paths.Attribute(attrb).value
foreach(var paths in commandcheck)
{
   Console.WriteLine(paths)
}

基本上我尝试解析和显示此数据的方式是

Command name Check
stdout output_value

command name config
stdout initialized
stdout listen
stdout loaded 

等等

谢谢。

你可以使用Element方法得到你想要的输出。

var textcheck = from paths in xd.Descendants("command") select paths.Element("commandoutput").Value;
foreach (var paths in textcheck)
{
   Console.WriteLine(paths);//Here you get output as 'TEXT'
}