我遇到了从控制台输入值中列出正确值的麻烦。我的XML文件是:
<Students>
<Student>
<Name>Name1</Name>
<Surname>Surname1</Surname>
<Index>2222</Index>
<Subject name="History">
<Class>Class2</Class>
<Status status="passed">
<Grade>A</Grade>
</Status>
</Subject>
</Student>
<Student>
<Name>Name2</Name>
<Surname>Surname2</Surname>
<Index>3333</Index>
<Subject name="Math">
<Class>Class3</Class>
<Status status="passed">
<Grade>D</Grade>
</Status>
</Subject>
</Student>
</Students>
所以我要做的是当我输入例如3333时,我想列出学生所属的班级,在这种情况下是“Class3”。我的代码是这样的:
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load("Students.xml");
Console.WriteLine("\nInsert Index Number");
string result = Console.ReadLine();
XmlNodeList xnList = xmlDoc.SelectNodes("//Student/Index");
XmlNodeList xnList2 = xmlDoc.SelectNodes("//Student/Subject/Class");
string result2 = null;
for (int i = 0; i < xnList.Count; i++)
{
string nodeval = xnList[i].InnerText;
if (nodeval == result)
for (int j = 0; j < xnList2.Count; j++)
{
result2 = xnList2[j].InnerText;
Console.WriteLine("Result" + result2);
}
}
}
有任何帮助吗? 感谢
答案 0 :(得分:0)
以下是你的答案。这基本上表示您希望所有具有父索引节点的Class节点的值为“3333”。您不需要使用2个节点集进行嵌套FOR循环来查找匹配项。
/Students/Student//Class[../..//Index[.="3333"]]
or
/Students/Student//Class[../../Index[.="3333"]]
or
//Student//Class[../../Index[.="3333"]]
您可以通过网址 http://www.xpathtester.com/test 对此进行测试 将我的XPath表达式粘贴到XPath文本框中,将XML粘贴到XML大文本框中,然后单击“测试!”按钮。
如果您需要完整的源代码,请在下面。关键是要创建正确的XPATH表达式,并使用您称为“索引”的变化值进行字符串替换/串联。这将返回所有Class节点,其值从您命名为Index的命令行输入。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load("Students.xml");
Console.WriteLine("\nInsert Index Number");
string index = Console.ReadLine();
//the critical piece is here, creating the correct xpath expression
string xPathString = String.Format("/Students/Student//Class[../..//Index[.=\"{0}\"]]", index);
XmlNodeList nodeList = xmlDoc.SelectNodes(xPathString);
foreach (XmlNode node in nodeList)
{
Console.WriteLine("Index: {0} Class: {1}", index, node.InnerText);
}
Console.ReadLine();
}
}
}