简体   繁体   English

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

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

Sorry if this has been asked I can't find it. 抱歉,如果有人问我找不到它。 I'm not great with XML but am trying to work with it 我对XML不太满意,但正在尝试使用XML

The xml looks like this: 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>

basically I am trying to get where the text is in the stdout under each command. 基本上我试图在每个命令下获取文本在stdout中的位置。

I've figured out I can get where it says "name of command" by doing 我已经知道我可以通过以下方式获得“命令名称”的显示位置

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)
}

Basically how I am attempting to parse and display this data is in the format of 基本上,我尝试解析和显示此数据的方式为

Command name Check
stdout output_value

command name config
stdout initialized
stdout listen
stdout loaded 

and so on 等等

Thanks. 谢谢。

You can use Element method to get your desire output. 您可以使用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'
} 

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

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