C# 从 XML 读取和存储数据

C# Read and Store Data from XML

我正在尝试从 xml 文件中读取和存储数据。我一直在阅读有关读取数据的各种方法,例如 XmlReader、XmlTextReader、LinQ 等。 我的 XML 文件是

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <circuit name="local">
      <Device>device1</Device>
      <Point>point1></Point>
    </circuit>
    <circuit name ="remote">
      <Device>device2</Device>
      <Point>point2</Point>
    </circuit>
</configuration>

我正在尝试提取设备和点集,以便我可以将它们传递给数据库查询。我使用这段代码和 foreach 循环来验证内容,但它只获取第一组。

XDocument msrDoc = XDocument.Load("BNOC MSR.config");
var data = from item in msrDoc.Descendants("circuit")
           select new
           {
               device = item.Element("Device").Value,
               point = item.Element("Point").Value
           };
foreach (var p in data)
   Console.WriteLine(p.ToString());

我也试过这个,但是我的数组都是空的

 String[] deviceList = new String[1];
 String[] pointList = new String[1];
 int n = 0;

 XmlDocument msrDoc = new XmlDocument();
 msrDoc.Load("BNOC MSR.config");
 var itemNodes = msrDoc.SelectNodes("circuit");
 foreach (XmlNode node in itemNodes)
 {
     var circuit = node.SelectNodes("circuit");
     foreach (XmlNode cir in circuit)
     {
         deviceList[n] = cir.SelectSingleNode("Device").InnerText;
         pointList[n] = cir.SelectSingleNode("Point").InnerText;
     }
 }

如有任何帮助,我们将不胜感激。

您确定不想为此使用内置 Properties.Settings 吗?

Circuit local = Properties.Settings.Default.localCircuit;
Circuit remote = Properties.Settings.Default.remoteCircuit;

https://docs.microsoft.com/en-us/dotnet/framework/winforms/advanced/using-application-settings-and-user-settings

我认为您测试结果的方式有问题。代码:

void Main()
{
    var fileLocation = @"C:\BrianTemp\input.txt";
    var xml = File.ReadAllText(fileLocation);

    XDocument msrDoc = XDocument.Load(fileLocation);
    var data = from item in msrDoc.Descendants("circuit")
               select new
               {
                   device = item.Element("Device").Value,
                   point = item.Element("Point").Value
               };
    foreach (var p in data)
    {
        //It is best practice to use statement blocks {} to prevent silly errors.  
        //Sometimes you want to execute multiple statements, especially as code changes later
        Console.WriteLine($"{p}");
    }

}

产生预期的输出:

{ device = device1, point = point1 }
{ device = device2, point = point2 }

你说:

I used this code and the foreach loop to verify the contents, but it only gets the first set.

如您所见,代码产生了 2 个结果。

注意:我更正了 XML 文件以删除多余的 >

<Point>point1></Point><==

我发现你的代码有两个问题(我只尝试了你发布的第二种方法):

  1. 你的字符串数组太小,改为:

    String[] deviceList = new String[1]; String[] pointList = new String[1];

  2. var itemNodes = msrDoc.SelectNodes("circuit");应该是

    var itemNodes = msrDoc.SelectNodes("configuration");