简体   繁体   中英

How can I get the type of element being processed by LINQ-to-XML?

With LINQ I get four elements out of some XML, each element can have a different name (Book, Magazine, Article).

How do I get the name of the element I'm currently processing, eg something like ElementType() below:

using System;
using System.Linq;
using System.Xml.Linq;

namespace TestXmlElement2834
{
    class Program
    {
        static void Main(string[] args)
        {

            XElement content = new XElement("content",
                new XElement("book", new XAttribute("id", "1")),
                new XElement("article", new XAttribute("id", "2")),
                new XElement("book", new XAttribute("id", "3")),
                new XElement("magazine", new XAttribute("id", "4"))
                );

            var contentItems = from contentItem in content.Descendants()
                               select new ContentItem
                               {
                                   Id = contentItem.Attribute("id").Value
                                   Type = contentItem.ElementType() //PSEUDO-CODE
                               };

            foreach (var contentItem in contentItems)
            {
                Console.WriteLine(contentItem.Id);
            }

            Console.ReadLine();
        }
    }

    class ContentItem
    {
        public string Id { get; set; }
        public string Type { get; set; }
    }

}

您需要XElement.Name

Is XElement.Name what you're after? (Use the XName.LocalName property to then get the local part of the element name.)

If you could say what you want the output to be, that would help :) (I originally thought you meant the type of node (attribute, element etc), but it'll always be XElement in your case...)

Try this:

var contentItems = from contentItem in content.Descendants()
                   select new ContentItem
                   {
                        Id = contentItem.Attribute("id").Value,
                        Type = contentItem.Name.LocalName
                   };

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