这是我读取单个节点的两个属性的代码。
这是我的Xml文件。
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<Users>
<User Name="aa" Occupation="dd" Date_Of_Birth="123456" NIC="123123" ID="79461" />
<User Name="Ali Rasheed" Occupation="Student" Date_Of_Birth="111694" NIC="4550246607037" ID="12661" />
<User Name="Asif Rasheed" Occupation="Civil Engineer" Date_Of_Birth="241190" NIC="4550346603073" ID="90939" />
</Users>
代码:
private void button1_Click(object sender, EventArgs e)
{
XDocument doc = XDocument.Load(@"C:\GenesisSolutionsCRMSBuild12101\XMLDatabase.xml");
var idExist = (doc.Descendants("User").Any(x => (string)x.Attribute("ID") == txtId.Text));
if (idExist)
{
var nicExist = doc.Descendants("User").Any(x => (string)x.Attribute("NIC") == txtNic.Text);
if (nicExist)
{
new formMainMenu().Show();
Hide();
}
else
{
MessageBox.Show("Invalid NIC", "Member Login - Genesis Solutions CRMS");
}
}
else
{
MessageBox.Show("Invalid ID", "Member Login - Genesis Solutions CRMS");
}
}
我想检查单个节点是否有两个属性。 如果我输入id 121661和nic 4550246607037,它应该说是,节点中存在值。
答案 0 :(得分:0)
你能不能在Any
中检查两者?
var bothExist = (doc.Descendants("User").Any(x => (string)x.Attribute("ID") == txtId.Text &&
(string)x.Attribute("NIC") == txtNic.Text);
答案 1 :(得分:0)
您可以使用OR,但是您必须确定一个或两个项目是否匹配。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
string input =
"<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>" +
"<Users>" +
"<User Name=\"aa\" Occupation=\"dd\" Date_Of_Birth=\"123456\" NIC=\"123123\" ID=\"79461\" />" +
"<User Name=\"Ali Rasheed\" Occupation=\"Student\" Date_Of_Birth=\"111694\" NIC=\"4550246607037\" ID=\"12661\" />" +
"<User Name=\"Asif Rasheed\" Occupation=\"Civil Engineer\" Date_Of_Birth=\"241190\" NIC=\"4550346603073\" ID=\"90939\" />" +
"</Users>";
XDocument doc = XDocument.Parse(input);
long searchID = 121661;
long searchNic = 455024660703;
var results = doc.Descendants ("User").Where(x => (long.Parse(x.Attribute("NIC").Value) == searchNic) || long.Parse(x.Attribute("ID").Value) == searchID)
.Select(y => new {id = long.Parse(y.Attribute("ID").Value), nic = long.Parse(y.Attribute("NIC").Value)}).ToList();
}
}
}