<Area>
<ShopA>
<Income Day="1" Money="100" />
<Income Day="2" Money="90" />
<Income Day="3" Money="80" />
<Income Day="4" Money="70" />
</ShopA>
<ShopB>
<Income Day="3" Money="50" />
<Income Day="4" Money="40" />
</ShopB>
</Area>
您好我希望通过使用XDocument从上面的XML中获取特定值。我希望从不同的商店获得具有相同日的所有 Money 值。我只能从单一商店(ShopA)获得日和金钱价值。
XDocument doc = XDocument.Load(xmlFileName.xml);
var areaName = doc.Root.Elements("Area");
IEnumerator<XElement> s = areaName.Elements("ShopA").GetEnumerator();
While (s.MoveNext())
{
var day = s.Current.Attribute("Day").Value;
var money = s.Current.Attribute("Money").Value;
}
但我不知道如何从不同的商店获得所有Money值,这些值与正确的编码具有相同的日期。
你能帮我解决一下这些问题吗?
提前致谢
答案 0 :(得分:1)
也许是这样的事情?
var doc = XDocument.Load("XMLFile1.xml");
var q =
doc.Root
.Elements()
.Elements()
.Where(e => e.Attribute("Day").Value == "3")
.Select(e => new
{
Shop = e.Parent.Name,
Money = e.Attribute("Money").Value
});
foreach (var e in q)
{
Console.WriteLine("{0} {1}", e.Shop, e.Money);
}
或者,如果您想获取所有日期的数据而不是查询一天:
var doc = XDocument.Load("XMLFile1.xml");
var q =
doc.Root
.Elements()
.Elements()
.Select(e => new
{
Day = e.Attribute("Day").Value,
Shop = e.Parent.Name,
Money = e.Attribute("Money").Value
})
.GroupBy(r => r.Day);
foreach (var e in q)
{
Console.WriteLine("Day: {0}", e.Key);
foreach (var i in e)
{
Console.WriteLine("{0} {1}", i.Shop, i.Money);
}
}
答案 1 :(得分:0)
尝试这样的事情:
<Area>
<ShopA>
<Income Day="1" Money="100" />
<Income Day="2" Money="90" />
<Income Day="3" Money="80" />
<Income Day="4" Money="70" />
</ShopA>
<ShopB>
<Income Day="3" Money="50" />
<Income Day="4" Money="40" />
</ShopB>
</Area>
var moneyDayResultSet = from Income in doc.Descendants("Income")
select new {
Money = Income.Attribute("Money").Value,
Day = Income.Attribute("Day").Value
};
//Loop through results
foreach (var moneyDayResult in moneyDayResultSet){
if(moneyDayResult.Day == 3)
{
Console.Write(moneyDayResult.Money);
}
}
答案 2 :(得分:0)
您可以在某一天通过XPath获得商店里的所有资金:
XElement root = XElement.Load(file);
string day = "2";
var shops = root.XPathSelectElements(
string.Format("//Income[@Day='{0}']", day))
.Select(x => new
{
Shop = x.Parent.LocalName,
Money = x.Attribute("Money").Value
});
使用以下命令找到.Net中的XPath:
使用System.Xml.XPath;