Tag Archives: LINQ

Parsing XML ma LINQ

Hawn eżempju ta 'malajr bl-użu LINQ li parse xi  XML u jiksbu fil-ħelu, attributi ħelu hemmhekk.

Hawn il-XML Irrid parse:

<?xml version="1.0" encoding="utf-8" ?>
<DeafultConfigurationSets>
  <PageLayouts>

    <PageLayout name="xyzzy">
      <Tabs>
        <Tab TabOrder="1" TabLabel="x" SharePointContentType="a" AdditionalConstraints="ac1"/>
        <Tab TabOrder="2" TabLabel="y" SharePointContentType="b" AdditionalConstraints="ac2"/>
      </Tabs>
    </PageLayout>

    <PageLayout name="xyzzy2">
      <Tabs>
        <Tab TabOrder="100" TabLabel="x" SharePointContentType="a" AdditionalConstraints="ac1"/>
        <Tab TabOrder="101" TabLabel="y" SharePointContentType="b" AdditionalConstraints="ac2"/>
        <Tab TabOrder="103" TabLabel="z" SharePointContentType="c" AdditionalConstraints="ac3"/>
      </Tabs>
    </PageLayout>

  </PageLayouts>
</DeafultConfigurationSets>

Irrid li jibnu xi tabs fil runtime mill parsing ta 'hawn fuq.  Tabs tiegħi jiddependu fuq tqassim paġna.  Jekk l-isem tqassim paġna tiegħi huwa "xyzzy2" imbagħad I rridu nġibu tabs 100, 101 u 103 (l-tabs fil <PageLayout isem = "xyzzy2">).

Hawn il-LINQ li tagħmlu:

kien allTabs =
              minn p fis
                  XElement.Parse(theXmlToParse).
                 
Elementi("PageLayouts").
                  Elementi("PageLayout")
              fejn (p.Attribute("name").Value.Equals("xyzzy2"))
              minn m p.Elements("Tabs").Elementi("Tab")
              tagħżel m;

          Results.Text = string.Empty;

          foreach (kien ATAB fis allTabs)
          {
              Results.Text =
                  "Tab Order: " + aTab.Attribute("TabOrder").Valur + " |" +
                  "Tab Label: " + aTab.Attribute("TabLabel").Valur + " | " +
                  "SharePointContentType: " + aTab.Attribute("SharePointContentType").Valur + " | " +
                  "AdditionalConstraints: " + aTab.Attribute("AdditionalConstraints").Valur + "\r";
          }

Fil-hawn fuq, il-varjabbli "theXmlToParse" hija varjabbli string, iżda tista 'tuża t-tagħbija() metodu fuq nixxiegħa jekk inti tixtieq.

"Riżultati" hija tikketta fuq formola web u meta dan il-kodiċi tesegwixxi, jidher qisu dan:

SNAGHTML11cd2e7c

I ma jkunux ħadmu kif biex issolvi r-riżultati għadhom, so I ser jitlaq minn dak għal blog post futur.

</aħħar>

Abbona għall-blog tiegħi.

Follow lili Twitter fi http://www.twitter.com/pagalvin