如何从xml中检索唯一值
本文关键字:检索 唯一 xml | 更新日期: 2023-09-27 18:28:38
我编写了一个查询,使用foreach检索不同的xml节点值
我正在尝试从XML
检索不同的BankName和TemplateModel有没有一种更好的方法可以用ienumerable或类似的东西编写查询
我的Xml如下
<Bank>
<BankName BankName="DohaBank" TemplateModel="CT1">
<ChqBasics>
</ChqBasics>
<XandYPosition>
</XandYPosition>
</BankName>
<BankName BankName="DohaBank" TemplateModel="CT2">
<ChqBasics>
</ChqBasics>
<XandYPosition>
</XandYPosition>
</BankName>
<BankName BankName="IBQ" TemplateModel="CT1New">
<ChqBasics>
</ChqBasics>
<XandYPosition>
</XandYPosition>
</BankName>
我的c#代码
public List<string> bankload()
{
List<string> bankname=new List<string>();
XDocument doc = XDocument.Load("newtest.xml");
var result= (from item in doc.Descendants("BankName")
select (string)item.Attribute("BankName")).Distinct();
foreach (var item in result)
{
bankname.Add(item.ToString());
}
return bankname;
}
public static List<string> templateload(string bankname)
{
List<string> templatename = new List<string>();
XDocument doc = XDocument.Load("newtest.xml");
var result = (from item in doc.Descendants("BankName")
where item.Attribute("BankName").Value == bankname
select (string)item.Attribute("TemplateModel")).Distinct();
foreach (var item in result)
{
templatename.Add(item.ToString());
}
return templatename;
}
我需要将结果绑定到组合框
为什么不这样做?
public List<string> bankload()
{
return
(
from item in XDocument.Load("newtest.xml").Descendants("BankName")
select (string)item.Attribute("BankName")
)
.Distinct()
.ToList();
}
public static List<string> templateload(string bankname)
{
return
(
from item in XDocument.Load("newtest.xml").Descendants("BankName")
where item.Attribute("BankName").Value == bankname
select (string)item.Attribute("TemplateModel")
)
.Distinct()
.ToList();
}
你是说像这样的羊羔肉吗?
public List<string> bankload()
{
return
XDocument
.Load("newtest.xml")
.Descendants("BankName")
.Select(item => (string)item.Attribute("BankName"))
.Distinct()
.ToList();
}
public static List<string> templateload(string bankname)
{
return
XDocument
.Load("newtest.xml")
.Descendants("BankName")
.Where(item => item.Attribute("BankName").Value == bankname)
.Select(item => (string)item.Attribute("TemplateModel"))
.Distinct()
.ToList();
}
返回XML:中不同BankName/TemplateModel组合的列表
var result = doc.Descendants("BankName")
.Select(bn => new
{
BankName = bn.Attribute("BankName").Value,
TemplateModel = bn.Attribute("TemplateModel")
.Value
});