C# 从 XML 中读取和存储数据

标签 c# xml visual-studio linq visual-studio-2008

我正在尝试从 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://learn.microsoft.com/en-us/dotnet/framework/winforms/advanced/using-application-settings-and-user-settings

关于C# 从 XML 中读取和存储数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50221727/

相关文章:

c# - 像å这样的C#字母未正确显示在输出文件中

c# - 如何优化XML的书写方式?

c# - Stackpanel 中的用户控件失去焦点

xml - xpath 表达式 "@*"是什么意思?

ios - 使用 xml 在 iOS 5 应用程序上创建文件,将数据导出到 *.xls 文件

visual-studio - 用于 AS/400 RPGILE 编程的最佳 IDE 是什么?您可以使用 Visual Studios IDE 连接到 400 吗?

python - Visual C++ Redistributable 2015 已删除且无法重新安装

c++ - VC++ 编译器/源字符集 :utf-8 doesn't work

c# - 使用 Begin* End* 方法时,在 C# 中处理数据包碎片的工作示例是什么样的?

c# - 在 BackgroundWorker doWork 事件中使用 Console.WriteLine