<?xml version="1.0" encoding="utf-8"?>
<Products>
<Item>
<ID>4</ID>
<GoodID>1552</GoodID>
<Price>3.85</Price>
<ZK>0.35</ZK>
<Quantity>1</Quantity>
</Item>
<Item>
<ID>5</ID>
<GoodID>1552</GoodID>
<Price>3.19</Price>
<ZK>0.29</ZK>
<Quantity>12</Quantity>
</Item>
<Item>
<ID>6</ID>
<GoodID>1552</GoodID>
<Price>3.19</Price>
<ZK>0.20</ZK>
<Quantity>34</Quantity>
</Item>
</Products>用LINQ TO XML 方式从中获取ID 及数量 存在的 ZK
比如:ID=1552且 数量=12 返回折扣 0.29
要求是:ID=1552 且数量=13 返回 0.29 但是 数量=34 返回0.20
<Products>
<Item>
<ID>4</ID>
<GoodID>1552</GoodID>
<Price>3.85</Price>
<ZK>0.35</ZK>
<Quantity>1</Quantity>
</Item>
<Item>
<ID>5</ID>
<GoodID>1552</GoodID>
<Price>3.19</Price>
<ZK>0.29</ZK>
<Quantity>12</Quantity>
</Item>
<Item>
<ID>6</ID>
<GoodID>1552</GoodID>
<Price>3.19</Price>
<ZK>0.20</ZK>
<Quantity>34</Quantity>
</Item>
</Products>用LINQ TO XML 方式从中获取ID 及数量 存在的 ZK
比如:ID=1552且 数量=12 返回折扣 0.29
要求是:ID=1552 且数量=13 返回 0.29 但是 数量=34 返回0.20
{
string xml = @"<?xml version=""1.0"" encoding=""utf-8""?>
<Products>
<Item>
<ID>4</ID>
<GoodID>1552</GoodID>
<Price>3.85</Price>
<ZK>0.35</ZK>
<Quantity>1</Quantity>
</Item>
<Item>
<ID>5</ID>
<GoodID>1552</GoodID>
<Price>3.19</Price>
<ZK>0.29</ZK>
<Quantity>12</Quantity>
</Item>
<Item>
<ID>6</ID>
<GoodID>1552</GoodID>
<Price>3.19</Price>
<ZK>0.20</ZK>
<Quantity>34</Quantity>
</Item>
</Products>";
XElement xmlPage = XElement.Parse(xml);
var query = from x in xmlPage.Descendants("Item")
select new
{
ID=x.Element("GoodID").Value,
Quantity=x.Element("Quantity").Value,
ZK=x.Element("ZK").Value
};
query.ToList().ForEach(q=>Console.WriteLine("ID="+q.ID+" Quantity=" +q.Quantity+" ZK="+q.ZK));
/*
ID=1552 Quantity=1 ZK=0.35
ID=1552 Quantity=12 ZK=0.29
ID=1552 Quantity=34 ZK=0.20 */
}
var query = xmlPage.Descendants("Item").Select(x => new
{
ID = x.Element("ID").Value,
GoodID = x.Element("GoodID").Value,
Quantity = x.Element("Quantity").Value,
ZK = x.Element("ZK").Value
});
void Main()
{
Console.WriteLine(GetZK(1552,12)); //0.29
Console.WriteLine(GetZK(1552,34)); //0.20
}
string GetZK(int id,int Quantity)
{
string xml = @"<?xml version=""1.0"" encoding=""utf-8""?>
<Products>
<Item>
<ID>4</ID>
<GoodID>1552</GoodID>
<Price>3.85</Price>
<ZK>0.35</ZK>
<Quantity>1</Quantity>
</Item>
<Item>
<ID>5</ID>
<GoodID>1552</GoodID>
<Price>3.19</Price>
<ZK>0.29</ZK>
<Quantity>12</Quantity>
</Item>
<Item>
<ID>6</ID>
<GoodID>1552</GoodID>
<Price>3.19</Price>
<ZK>0.20</ZK>
<Quantity>34</Quantity>
</Item>
</Products>";
XElement xmlPage = XElement.Parse(xml);
var query = (from x in xmlPage.Descendants("Item")
where x.Element("GoodID").Value.Equals(id.ToString())
&& x.Element("Quantity").Value.Equals(Quantity.ToString())
select x.Element("ZK").Value).FirstOrDefault();
return query==null?"":query;
}
var query = from x in xel.Descendants("Item")
where (string)x.Element("GoodID").Value.Equals(id)
&& x.Element("Quantity").Value.Equals(Quantity)
select x.Element("ZK").Value;