简体   繁体   English

读取XML节点并添加到datagrid

[英]Reading XML nodes and add to datagrid

I have a XML file with settings. 我有一个带有设置的XML文件。 I would like to read the the name and value of all CollectionEntry nodes and add them to a DataGrid. 我想读取所有CollectionEntry节点的namevalue ,并将它们添加到DataGrid。

I think a good way is to use a List and fill it with the name and values of the XML file and then add it to the DataGrid, like this: 我认为一个好方法是使用一个List并用XML文件的名称和值填充它,然后将其添加到DataGrid中,如下所示:

List<Buffer> buffers = new List<Buffer>();
buffers.Add(new Buffer(){bufferName="username_testuser1",bufferValue="testuser2"});
bufferGrid.DataSource = buffers;

public class Buffer
{
  public string bufferName { get; set; }
  public string bufferValue { get; set; }
}

But how can I read the specific CollectionEntry values? 但是,如何读取特定的CollectionEntry值? This is the XML file: 这是XML文件:

<?xml version="1.0" encoding="utf-8"?>
<Settings xmlns="Namespace" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <Category name="Commander">
    <Category name="ManualTestExecution">
      <Setting name="WindowLocation" legacyPath="Commander.GUI.ManualTestExecution.WindowLocation">336,263</Setting>
      <Setting name="WindowSize" legacyPath="Commander.GUI.ManualTestExecution.WindowSize">732,451</Setting>
    </Category>
  </Category>
  <Category name="Engine">
    <Setting name="Key Delay" legacyPath="BaseSettings.keyDelay">1</Setting>
    <Setting name="Wait Intermediate" legacyPath="BaseSettings.waitIntermediate">5000</Setting>
    <Setting name="Report Successful Execution of" legacyPath="XML.OutputLogLevel">2</Setting>
    <Collection name="Buffer" legacyPath="Buffer.Local">
      <CollectionEntry name="username_testuser1">testuser2</CollectionEntry>
      <CollectionEntry name="password_testuser1">!Welcome099</CollectionEntry>
      <CollectionEntry name="username_testuser2">testuser2</CollectionEntry>
    </Collection>
  </Category>
</Settings>

Using LINQ to XML you can use 使用LINQ to XML,您可以使用

XNamespace df = "Namespace";

List<Buffer> buffers = new List<Buffer>(from entry in XDocument.Load("yourFile.xml").Descendants(df + "CollectionEntry") select new Buffer( bufferName = (string)entry.Attribute("name"), bufferValue = (string)entry));

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

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