read XML using LINQ
I am newbie to LINQ. I am trying to read the following node and element values from XML using LINQ.
DATA -- msgid and msgtime PTP -- percentage CONT1 -- get "url" value if the "type" = "RIGHT"
Please let me know.
<DATA msgid="02123" msgtime="2008-02-29 15:30:02.123">
<PTP number="67" pert="READ" percentage="95" pertime="2008-02-29 15:30:02.123">
<Images>
<Image view="w1" type="IMAGE" percentage="85" distance="0" url="00002_tyd.jpg" />
</Images>
</PTP>
<CHAS1 sequence="1" number="58019" percentage="95" pertime="2008-02-29 15:30:02.123">
<Images>
<Image view="c1" type="WRONG" percentage="85" url="00002_ssj.jpg" />
<Image view="c2" type="RIGHT" percentage="85" url="00003_ssj.jpg" />
</Images>
<开发者_如何学CCONT1 number="58011" percentage="95" pertime="2008-02-29 15:30:02.123">
<Images>
<Image view="c1" type="WRONG" percentage="85" url="00002_csj.jpg" />
<Image view="c2" type="RIGHT" percentage="85" url="00003_csj.jpg" />
</Images>
</CONT1>
</CHAS1>
</DATA>
I would suggest you take a look at this:
http://www.hookedonlinq.com/LINQtoXML5MinuteOverview.ashx
Particularly the part beginning with "Once these files are loaded into the LINQ to XML API, you can write queries over that tree."
Based on that, something like this should work for you:
XDocument loaded = XDocument.Load(@"C:\data.xml");
var q = from c in loaded.Descendants("DATA")
select new
{
MsgId = (int)c.Attribute("msgid"),
MsgTime = (DateTime)c.Attribute("msgtime"),
PtpPercentage = (int)c.Element("PTP").Attribute("percentage")
ContUrls = from i in c.Element("CHAS1")
.Element("CONT1")
.Descendants("Image")
where (string)i.Attribute("type") == "RIGHT"
select (string)i.Attribute("url");
};
Not tested, but that should put you on the right track.
精彩评论