我需要从本地VS2013项目中读出一个xml文件。我已经访问了我的文件,但没有访问xml-file-content并且总是得到console-output:"清空列表"。我无法找到错误......:/
这是我的xml文件:
<SystemParameters>
<Velocities>
<Axis>
<Name>V1</Name>
<DefaultValue>v1</DefaultValue>
</Axis>
<Axis>
<Name>V2</Name>
<DefaultValue>v2</DefaultValue>
</Axis>
<Axis>
<Name>V3</Name>
<DefaultValue>v3</DefaultValue>
</Axis>
</Velocities>
<Lengths>
<Axis>
<Name>L1</Name>
<DefaultValue>l1</DefaultValue>
</Axis>
<Axis>
<Name>L2</Name>
<DefaultValue>l2</DefaultValue>
</Axis>
<Axis>
<Name>L3</Name>
<DefaultValue>l3</DefaultValue>
</Axis>
</Lengths>
</SystemParameters>
这是我的C#代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Xml;
using System.Xml.Linq;
using System.Reflection;
namespace Untitled
{
public class Program
{
public static List<string> ReadoutVelocities(XElement parameters)
{
List<string> velocitiesList = new List<string>();
var velocity = from s in parameters.Elements()
select s.Element("Velocities");
foreach (var p in velocity.Elements("Axis"))
{
velocitiesList.Add(p.Element("Name").Value);
velocitiesList.Add(p.Element("DefaultValue").Value);
}
return velocitiesList;
}
public static void Query(XElement parameters)
{
Console.WriteLine("Readout all velocity-parameters:\n");
List<string> resultList = new List<string>();
resultList = ReadoutVelocities(parameters);
if(resultList.Count == 0)
Console.WriteLine("Empty list");
else
{
for (int i = 0; i < resultList.Count; i++)
{
Console.WriteLine("Name: " + resultList.ElementAt(i));
Console.WriteLine("DefaultValue: " + resultList.ElementAt(i + 1) + "\n");
}
Console.WriteLine("\n- - - - - End-Of-Line- - - - - \n");
}
}
static void Main()
{
var asm = Assembly.GetExecutingAssembly();
var textStream = asm.GetManifestResourceStream("Untitled.DefaultValues.xml");
var xmlReader = new XmlTextReader(textStream);
XElement parameters = XElement.Load(xmlReader);
Query(parameters);
Console.Read();
}
}
}
答案 0 :(得分:1)
有2袋
resultList.Count
应少这里的完整版
public static void Query(XElement parameters)
{
Console.WriteLine("Readout all velocity-parameters:\n");
var resultList = new List<string>();
resultList = ReadoutVelocities(parameters);
if (resultList.Count == 0)
{
Console.WriteLine("Empty list");
}
for (int i = 0; i < resultList.Count/2; i++)
{
Console.WriteLine("Name: " + resultList.ElementAt(i));
Console.WriteLine("DefaultValue: " + resultList.ElementAt(i + 1) + "\n");
}
Console.WriteLine("\n- - - - - End-Of-Line- - - - - \n");
}
public static List<string> ReadoutVelocities(XElement parameters)
{
var velocitiesList = new List<string>();
IEnumerable<XElement> velocity = parameters.Descendants("Velocities");
foreach (XElement p in velocity.Elements("Axis"))
{
velocitiesList.Add(p.Element("Name").Value);
velocitiesList.Add(p.Element("DefaultValue").Value);
}
return velocitiesList;
}
结果输出:
Readout all velocity-parameters:
Name: V1
DefaultValue: v1
Name: v1
DefaultValue: V2
Name: V2
DefaultValue: v2
- - - - - End-Of-Line- - - - -