C#从XML

时间:2018-05-07 20:10:35

标签: 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;
     }
 }

非常感谢任何帮助。

3 个答案:

答案 0 :(得分:0)

您确定不想使用内置的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

答案 1 :(得分:0)

我相信你测试结果的方式有问题。代码:

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 }

你说:

  

我使用此代码和foreach循环来验证内容,但它   只得到第一组。

正如您所看到的,代码会产生2个结果。

注意:我更正了XML文件以删除额外的>

<Point>point1></Point>&LT; ==

答案 2 :(得分:0)

我在你的代码中看到两个问题(我只尝试了你发布的第二个方法):

  1. 您的字符串数组太小,请更改为:

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

  2. var itemNodes = msrDoc.SelectNodes("circuit");行应为

    var itemNodes = msrDoc.SelectNodes(“configuration”);