<?xml version="1.0" encoding="utf-8" ?>
<questions>
<question num="1">Employees should be involved in setting their goals.</question>
<question num="2">Most people resists change.</question>
<question num="3">Manager should guide rather control.</question>
<question num="4">Average person is easily decieved.</question>
</questions>
如何将当前属性值设置为变量i,使用此当前属性i调用方法next()时,它应检索下一个节点值(例如,当下一个()时当前属性值为1调用它应该检索第二个节点值,当再次调用next()时,它应该使用System.Xml检索第三个属性值?
我曾尝试使用Xpath检索第一个节点值,但我不知道如何将当前属性值设置为变量,然后使用变量移动到下一个节点值。以下是我试过的代码。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml;
using System.Xml.XPath;
namespace ConsoleApplication14
{
interface IQuestion
{
void Question1();
void Next();
}
class Question : IQuestion
{
string BuildXpathQuery(int c)
{
string part1 = @"questions/question[@num='";
string part2 = @"']";
string MyQuery = part1 + c + part2;
return MyQuery;
}
public void Question1()
{
XmlDocument doc = new XmlDocument();
doc.Load("C:\\Users\\Murari\\Documents\\Visual Studio 2015\\Projects\\ConsoleApplication14\\ConsoleApplication14\\XMLFile1.xml");
XmlNode xnList = doc.SelectSingleNode(BuildXpathQuery(1));
if (xnList != null)
{
Console.WriteLine(xnList.InnerXml);
Console.ReadKey();
}
}
public void Next()
{
}
}
class Program
{
static void Main(string[] args)
{
IQuestion ques = new Question();
ques.Question1();
ques.Next();
}
}
}
答案 0 :(得分:0)
您只需创建一个List&lt;&gt;宾语。使用XML Linq是最好的方法
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;
namespace ConsoleApplication1
{
class Program
{
const string FILENAME = @"c:\temp\test.xml";
static void Main(string[] args)
{
XDocument doc = XDocument.Load(FILENAME);
var xnList = doc.Descendants("question").Select(x => new
{
num = (int)x.Attribute("num"),
text = x.Value
}).ToList();
foreach (var question in xnList)
{
}
}
}
}