简体   繁体   中英

Read multiple XML files into a XML class structure

I would like to Read and Deserialize more than one XML file into my XML class structure given a list of strings consisting of file names. Obviously when reading ONE xml file, you can go like this:

XmlRoot file = null;
XmlSerializer ser = new XmlSerializer(typeof(XmlRoot));
using (XmlReader read = XmlReader.Create(FileName))
{
    file = (XmlRoot)ser.Deserialize(read);
{

Which will deserialize the XML file into the class structure?

It is not possible to have a list with file names and use a foreach loop to iterate over them, reading and deserializing one by one as it would theoretically result into multiple root elements being read, deserialized and replicated in the class structure.

So in general I would like to deserialize each file and append the required master elements to a root object.

Does anyone know how to accomplish this? It would be of great help.

Thanks in advance!

PS: Excuse me for my English, as I am not a native speaker. If you need further information, just tell me!

I managed to solve the problem for myself. First i created a XDocument for the first file i read, afterwards i iterate through the other documents creating a new XDocument for every xml file and try to get the elements after the root (Language in my case) and add it to the root of the XDocument created outside the loop.

        XDocument lDoc = new XDocument();
        int counter = 0;
        foreach (var fileName in multipleFileNames)
        {
            try
            {
                counter++;
                if (lCounter <= 1)
                {
                    doc = XDocument.Load(fileName);
                }
                else
                {
                    XDocument doc2 = XDocument.Load(fileName);
                    IEnumerable<XElement> elements = doc2.Element("Language")
                        .Elements();

                    doc.Root.Add(elements);
                }
            }
            return Deserialize(lDoc);

Afterwards i call the Deserialize method, deserializing my created XDocument like this:

    public static XmlLanguage Deserialize(XDocument doc)
    {
        XmlSerializer ser = new XmlSerializer(typeof(XmlLanguage));
        return (XmlLanguage)ser.Deserialize(doc.CreateReader());
    }

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