【问题标题】:How to Retrieve value of xml node?如何检索xml节点的值?
【发布时间】:2012-12-21 05:35:20
【问题描述】:

我有一个这样的 xml 文件:

<Contacts>
   <CommandID>
       ShowInstalledProducts
   </CommandID>
</Contacts>

我需要遍历一个 xml 文件列表并为每个文件检索 CommandId 的值(在本例中为 ShowInstalledProducts)...

我对 xml 很陌生。有人可以帮助我吗?我正在尝试使用 Linq 来实现这一目标。 (不过也欢迎其他解决方案)

DirectoryInfo directoryInfo = new DirectoryInfo(@"T:\Commands"); FileInfo[] fileInfo = directoryInfo.GetFiles();

            foreach (FileInfo loop in fileInfo)
            {

                string doc = File.ReadAllText(loop.FullName);
                XmlDocument XMLDoc = new XmlDocument();
                XMLDoc.Load(doc);
                XMLDoc= stripDocumentNamespace(XMLDoc);
                //id = XMLDoc.Descendants("CommandID").First().Value;



            }

这就是我到目前为止所做的,我正在阅读文件,并试图让后代产生。但是每个 xml 文件中有多个,我需要检索每个的值。卡在这里:(

【问题讨论】:

  • 你有什么问题?您是否找不到有关 LINQ to XML 的任何信息?
  • 您需要向我们证明您已经尝试过某些事情或至少对您的问题进行了一些研究。
  • 你想以哪种方式读取xml文件意味着javascript。
  • 我刚刚编辑了我的问题,以展示我到目前为止所做的事情......

标签: c# xml linq


【解决方案1】:

第 1 步: 转到 linqpad.net 并下载 Linqpad 应用程序。它是一个简单的编辑器,允许您编写、运行和使用 Linq 表达式。此外,它还有很多内置示例可供学习。 (您可能需要select Help --&gt; Veiw samples 才能打开它):

第 2 步: 将以下代码粘贴到编辑器中,然后按 F5 键运行它(不过,请确保为上面的“语言”选择了 C# Statement(s)!)。随心所欲地尝试和调整它。

var bench = XElement.Parse(@"<Contacts>
                <Node>
                    Something
                </Node>
                <Node>
    Something else
                </Node>
                </Contacts>");

var listOfNodes = bench.Elements(); 
listOfNodes.Dump();

var content = listOfNodes.Select(x => x.Value); 
content.Dump();

这应该足以让您入门。享受! :)

【讨论】:

    【解决方案2】:
    fileInfo.SelectMany(fi => XDocument
                               .Load(fi.FullName)
                                  .Descendants("CommandID")
                                    .Select(e=>e.Value))
    

    此 LINQ 代码应返回所有文件的所有 CommandId 值的列表。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-02-22
      • 1970-01-01
      • 1970-01-01
      • 2018-08-27
      • 1970-01-01
      相关资源
      最近更新 更多