简体   繁体   中英

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>
    <CONT1 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM