我创建了一个C#Web表单应用程序,我希望从特定对象获取索引。这就是我现在所拥有的。在本练习中,我想输入登录名和密码以获取该特定人员的信息。允许重复的名称/密码。我能想到的是从节点获取索引,然后使用XmlNodeList info = reader.GetElementsByTagName("Info");
和textBox1.Text = root.GetElementsByTagName("Info")[index].InnerText;
我需要找到特定的索引,但我觉得有点混淆。希望有人能给我任何建议,以及如何做到的新想法,谢谢!
private int GetIndex(string loginname, string password)
{
reader = new XmlDocument();
reader.Load(@filepath);
XmlNodeList loginN = reader.GetElementsByTagName("Loginname");
XmlNodeList Pass = reader.GetElementsByTagName("Password");
}
XML:
<?xml version="1.0" encoding="utf-8"?>
<Authentication>
<User xmlns="">
<Loginname>Admin</Loginname>
<Password>232</Password>
<Info>Hello, I'm first person</Info>
</User>
<User xmlns="">
<Loginname>Admin</Loginname>
<Password>4445</Password>
<Info>Hello, I'm second person</Info>
</User>
</Authentication>
答案 0 :(得分:2)
如果您想通过给定Info
和Loginname
获得Password
,那么您可以使用XPath。
string username = "Admin";
string password = "232";
string xPathQuery =
String.Format("Authentication/User[Loginname='{0}' and Password='{1}']",
username, password);
XmlNode node = reader.SelectSingleNode(xPathQuery);
if (node == null)
{
// Incorrect username \ password
} else {
string info = node.SelectSingleNode("User/Info").InnerText;
textBox1.Text = info;
}
请注意,如果有多个Users
具有相同的用户名和相同的密码 - SelectSingleNode
将选择第一个。
答案 1 :(得分:0)
这样的事情:
XmlDocument doc = new XmlDocument();
doc.Load("XmlFile1.xml");
var node = doc.SelectSingleNode("Authentication/User[Loginname='Admin' and Password='4445']");
var childnodes = doc.DocumentElement.ChildNodes;
for (int i = 0; i < childnodes.Count; i++)
{
if (node == childnodes[i])
{
Console.WriteLine("INDEX IS: " + i);
}
}