Tag Archives: LINQ

Parsáil XML le LINQ

Seo sampla tapa ag baint úsáide as LINQ a pharsáil roinnt  XML agus a fháil ar an milis, tréithe milis ann.

Seo an XML a ba mhaith liom a pharsáil:

<?xml version = "1.0" ionchódú = "UTF-8" ?>
<DeafultConfigurationSets>
  <PageLayouts>

    <PageLayout-ainm = "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>

Ba mhaith liom a thógáil suas roinnt tabs ag runtime ag parsáil an méid sin thuas.  Mo tabs ag brath Ar an leagan amach na leathanach.  Is é mo ainm DM Leathanach leagan amach ar "xyzzy2" ansin ba mhaith liom a fháil tabs 100, 101 agus 103 (an tabs in <PageLayout ainm = "xyzzy2">).

Seo an LINQ go ndéanann sé:

var = allTabs
              ó p i
                  XElement.Parse(theXmlToParse).
                 
Eilimintí("PageLayouts").
                  Eilimintí("PageLayout")
              Nuair a (p.Attribute("name").Value.Equals("xyzzy2"))
              ó dom i p.Elements("Tabs").Eilimintí("Tab")
              Roghnaigh m;

          Results.Text = string.Empty;

          foreach (Bhí ATAB isteach allTabs)
          {
              Results.Text =
                  "Tab Order: " + aTab.Attribute("TabOrder").Luach + " |" +
                  "Tab Label: " + aTab.Attribute("TabLabel").Luach + " | " +
                  "SharePointContentType: " + aTab.Attribute("SharePointContentType").Luach + " | " +
                  "AdditionalConstraints: " + aTab.Attribute("AdditionalConstraints").Luach + "\r";
          }

Sa thuas, Is é an athróg "theXmlToParse" athróg teaghrán, ach is féidir leat úsáid a bhaint as an t-ualach() modh ar sruth más mian leat.

"Torthaí" Is é an lipéad ar fhoirm ngréasán Agus nuair a fhorghníomhú an gcód seo, tá sé cosúil leis an:

SNAGHTML11cd2e7c

Nach bhfuil mé ag obair amach conas a shórtáil na torthaí fós, mar sin beidh mé saoire Sin haghaidh a blog post amach anseo.

</deireadh>

Liostáil le mo bhlag.

Lean mé ar Twitter ag http://www.twitter.com/pagalvin