A
A
Avery0072013-11-18 17:27:20
C++ / C#
Avery007, 2013-11-18 17:27:20

[LINQ TO XML] How to get all elements from a document?

You need to get all the elements from the document as an IEnumerable.
I know about the Elements() function, but it only returns the children of an element. And I need all the ones I have.

Answer the question

In order to leave comments, you need to log in

5 answer(s)
T
Teacher, 2013-11-18
@Avery007

Good afternoon.
If you want to get all elements, including nested ones, as a single list, then you will have to recursively traverse the entire tree. Those. start, for example List and start bypassing all elements adding them to this List. Added? We run the same algorithm on their children.

A
Avery007, 2013-11-18
@Avery007

Well, this is clear to me.
But how can I get around this tree?

I
imlex, 2013-11-18
@imlex

You can use the XPathSelectElements method with the expression parameter equal to "//*". In theory it should work.

N
Nikolai Turnaviotov, 2013-11-19
@foxmuldercp

Linq 2 XML, you say?
Isn't it easier to immediately serialize the object tree with a couple of lines of code, like this:

public async Task<FileContentResult> Export()
{
// Выключаем Proxy при запросах, иначе сериализация выпадает с ошибкой.
            using (DefaultConnection conn = new DefaultConnection())
            {
                conn.Configuration.ProxyCreationEnabled = false;
// получаем нашу структуру с вложенными свойствами
                List<OurUnit> Units = conn.Units.Where(u => u.UserId == userId).Include(a => a.SubUnits).ToList();
                XmlSerializer serializer = new XmlSerializer(typeof(List<OurUnit>));
                StringWriter writer = new StringWriter();
                
                serializer.Serialize(writer, Units);

                System.Text.UnicodeEncoding encoding = new System.Text.UnicodeEncoding();
                byte[] writerToBytes = encoding.GetBytes(writer.ToString());
                FileContentResult file = new  FileContentResult(writerToBytes, "text/xml");
                file.FileDownloadName = CurrentUser.UserName + "  data " + DateTime.Now.ToString() + ".xml";
                conn.Configuration.ProxyCreationEnabled = true; 
                return file;
 }

T
Teacher, 2013-11-20
@Teacher

Here's a demo that traverses the entire tree and prints the element names to the screen.

class Program
{
    static void Main(string[] args)
    {
        List<XElement> elements = GetElementsFromFile(@"ConsoleApplication35.exe.config");
        foreach (var item in elements)
        {
            Console.WriteLine(item.Name);
        }
        Console.ReadKey();
    }

    public static List<XElement> GetElementsFromFile(string p_fileName)
    {
        List<XElement> list = new List<XElement>();
        BuildElementList(XElement.Load(p_fileName).Elements(), list);
        return list;
    }

    private static void BuildElementList(IEnumerable<XElement> p_elements, List<XElement> p_list)
    {
        foreach (var item in p_elements)
        {
            p_list.Add(item);
            var children = item.Elements();
            if (children.Any())
            {
                BuildElementList(children, p_list);
            }
        }
    }
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question