简体   繁体   中英

Create generic list from any XML file

The title explains most of it. What I am doing probably is not the best solution. I saw many websites saying that you should know the structure of the XML file. But my goal is this. I want to create ac# function that reads XML information to a list. I want to read the entire file, no matter the structure and keep it in memory.

I already built some code wich reaches every tag in the XML file and it works.

private void Form1_Load(object sender, EventArgs e)
{
    XDocument file = XDocument.Load("file.xml");

    foreach (XElement element in file.Root.Elements())
    {
        text += element.Name + Environment.NewLine;


        if (element.HasElements)
            readElement(element);
    }

    MessageBox.Show(text);
    Application.Exit();
}

private void readElement(XElement element)
{
    IEnumerable<XElement> nodes = element.Elements();

    foreach (XElement el in nodes)
    {
        text += el.Name + Environment.NewLine;

        if (element.HasElements)
            readElement(el);
    }
}

So lets say I have this XML file to read:

<?xml version="1.0" encoding="UTF-8"?>
<parent>
    <element1>
        <element2>
            <element3></element3>
        </element2>
    </element1>
    <element4>
        <element5></element5>
    </element4>
    <element6>
        <element7>
            <element8>
                <element9></element9>
            </element8>
        </element7>
    </element6>
</parent>

Like I said, i want the code to be able to work with any XML file, no matter the structure. So my function starts with the root, wich will be an empty list, don't even knowing the type. Since it has children elements, this list will create on fly a list inside it, with the children elements. After that, it will see every child and create a list inside it if it has children elements too.

So at the end, I will have lists inside lists, exactly like the structure of my file. This is where I'm stuck right now, trying to add these list attributes to the root list. Besides this, I also want to add an attribute with the name 'Value' and type 'object' to store the data inside the tag.

This may be a little confuse to understand and possibly impossible to do, but I just decided to try, since I couldn't find a generic code to read any XML file data on the internet.

Thanks for the help in advance. :)

To begin with I would probably use an XmlReader instead because I think the XDocument.Load will cause problems if the file you are trying to read is a big file.

using (XmlReader reader = XmlReader.Create(@"file.xml"))
{
    while (reader.Read())
    {
       // Process each node (myReader.Value) here
    }
}

Hope that helps somewhat at least...

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