简体   繁体   中英

Select descendent nodes and elements from an XML using LINQ

I have an XML file like this:

<BRPlugins>
  <Plugin name="aaaa">
      <summary>ssss</summary>
      <description>dddd</description>
      <category>cccc</category>
      <product>pppp</product>
      <gallery>
        <media type="picture" url="http://linktofolder/image.jpg">
        </media>
        <media type="picture" url="http://linktofolder/image.jpg">
        </media>
        <media type="video" url="http://linktofolder/video.avi">
        </media>
      </gallery>
      <Installers>
        <Release version="1234" status="production">
          <Installer url="http://linktofolder/installer1.exe"/>
          <Installer url="http://linktofolder/installer2.exe"/>
          <Installer url="http://linktofolder/installer3.exe"/>
        </Release>
        <Release version="4567" status="production">
          <Installer url="http://linktofolder/installer4.exe"/>
          <Installer url="http://linktofolder/installer5.exe"/>
          <Installer url="http://linktofolder/installer6.exe"/>/>
        </Release>
  </Plugin>
</Plugins>

I'm using XDocument to read the XML and create the HTML:

XDocument xmlDoc = XDocument.Load(Server.MapPath("Plugins.xml"));
foreach (XElement product in xmlDoc.Root.Nodes())
{
  counter++;
   div += "<div class='col-plugin-item alt" + counter + "'><a href='javascript:void(0)' class='name' id='box" + counter + "'>" + product.Attribute("name").Value + "</a></div>";
}
testediv.InnerHtml = div;

I need to be able to access the element "url" from media and Installer, and version and status from Release. I've tried the following but it doesn't work:

var childElements = xmlDoc.Descendants("gallery").Elements("media");

foreach (XElement en in childElements)
{
  div += "Descendents: " + en.Attributes("url");
}
testediv.InnerHtml = div;

Thanks!!!

When you call Attributes("url") , you're actually creating a collection even if there's only one element. Something like this should work better:

div += "Descendents: " + en.Attributes("url").First().Value;

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