查询特定数据的最佳方法是什么?
本文关键字:方法 是什么 最佳 数据 查询 | 更新日期: 2023-09-27 18:01:45
我知道这可能比我写的要容易得多。我能够从XElement中取出所有的机器,但我试图弄清楚如何取出具有特定序列号的机器。在下面的XML片段中,我想使用sequence = 1的机器。
XML:<Location>
<Sequence>1</Sequence>
<Machines>
<Machine></Machine>
<Machine></Machine>
</Machines>
</Location>
<Location>
<Sequence>2</Sequence>
<Machines>
<Machine></Machine>
<Machine></Machine>
</Machines>
</Location>
代码:IEnumerable<XElement> locSeqMachines =
from seq in LocationRows.Descendants("Location")
select seq;
var eMachines = locSeqMachines.Descendants("Machine");
foreach (var machine in eMachines)
{
}
应该这样做:
int soughtId = 1; // Assuming this is coming from somewhere
string soughtIdStr = soughtId.ToString();
var machines = LocationRows.Descendants("Location")
.Where(l => (string)l.Element("Sequence") ==
soughtIdStr)
.Descendants("Machine");
可以使用XPath按特定顺序选择节点:
XmlNodeList nodeList = root.SelectNodes("descendant::Location[Sequence='1']");
这段代码将根据Location的Sequence值筛选Location标签中的所有Machine数据分组:
var locSeqMachines = from seq in LocationRows.Descendants("Location")
where seq.Element("Sequence").Value == "1"
select new {
Sequence = seq.Element("Sequence").Value,
Machines = from m in seq.Descendants("Machines").Elements()
select m.Value
};
下面是一些代码,演示如何访问数据(并测试代码片段):
foreach (var location in locSeqMachines) {
Console.WriteLine("sequence: {0}", location.Sequence);
foreach (var machine in location.Machines) {
Console.WriteLine(" machine: {0}", machine);
}
}
在解析给定的xml时,可以使用此方法获得答案,而不会引发多个根元素的错误。
var xmlText = @"<root>
<Location>
<Sequence>1</Sequence>
<Machines>
<Machine></Machine>
<Machine></Machine>
</Machines>
</Location>
<Location>
<Sequence>2</Sequence>
<Machines>
<Machine></Machine>
<Machine></Machine>
</Machines>
</Location>
</root>";
var elements = XElement.Parse(xmlText);
var machineWith1 = from subElem in elements.Elements("Location")
where subElem.Element("Sequence").Value == "1"
select subElem.Element("Machines").Elements("Machine");
那么你可以检查machineWith1的值,