簡體   English   中英

使用LINQ讀取XML

[英]read XML using LINQ

我是LINQ的新手。 我正在嘗試使用LINQ從XML讀取以下節點和元素值。

數據-msgid和msgtime PTP-百分比CONT1-如果“ type” =“ RIGHT”,則獲取“ url”值

請告訴我。

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

我建議您看一下:

http://www.hookedonlinq.com/LINQtoXML5MinuteOverview.ashx

特別是從“一旦將這些文件加載​​到LINQ to XML API中,您就可以在該樹上編寫查詢了”。

基於此,這樣的事情應該為您工作:

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");
        };

未經測試,但這應該使您走上正確的道路。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM