1

I've got two XML files and I want to compare in a C# application. I am using XDocument and I want to load both XML files (which have static filenames and directories) and search and append an entry based on matching values. One of my XML files contains the following structure as shown below:

<Code>0000890</Code>
<Device_Name>Device1</Device_Name>
<Time>11:06:18.836 </Time>   </body>

The second XML file has a structure like this:

<ID>0000890</ID>
<FirstName>John</FirstName>
<LastName>Doe</LastName>   </body>

I want to read both files and match records where the ID and Code are the same but also append the first XML files with the additional details from the second XML file. So in matching cases id end up with:

<ID>0000890</ID>
<FirstName>John</FirstName>
<LastName>Doe</LastName>   
<Device_Name>Device1</Device_Name>
<Time>11:06:18.836 </Time>   </body>

Should i use a foreach loop and step through all the entries or what is the best approach? Any help would be greatly appreciated. Thank you

Crowcoder
  • 11,250
  • 3
  • 36
  • 45
cfcorp
  • 99
  • 2
  • 10
  • If you want to match all entries, use a loop. If you only want to match a single entry, see [Finding element in XDocument?](https://stackoverflow.com/questions/8460464/finding-element-in-xdocument). – Georg Patscheider Apr 04 '18 at 14:29

1 Answers1

0

Whenever I have to work with xml, I'd rather deserialize everything into objects so I can handle them in a type safe fashion.

In your case i would have this:

public class Item {
    public Int32 ID { get; set; }
    public String FirstName { get; set; }
    public String LastName { get; set; }
    public String DeviceName { get; set; }
    public TimeSpan Time { get; set; }

    public Item(XElement xElement) {
        Load(xElement);
    }

    public void Load(XElement xElement) {
        // your code to grab values goes here
    }

    public XElement ToXElement() {
        // your code to create the xml representation goes here
    }
}

Then I'd just grab all the relevant xml elements from your file and feed them into the constructors. You can use the ID property as the Key in a Dictionary<Int32, Item> and use Load(XElement) to update more data from other xml elements so that it merges multiple data sets. Then use ToXElement() to recreate the desired xml file with all your data.

Update: Also be sure to use XmlConvert when serializing and deserializing your values.

MikeLimaSierra
  • 799
  • 2
  • 11
  • 29