Search code examples
c#.netxmlserializationdeserialization

Error Deserializing Xml to Object when it is sometimes encased in another root


I am using XmlSerializer in order to deserialize an XML and it would encounter an error if there is a different root element.

For example, the following XML would deserialize correctly

<?xml version="1.0"?>
<customers>
   <customer id="55000">
      <name>Charter Group</name>
      <address>
         <street>100 Main</street>
         <city>Framingham</city>
         <state>MA</state>
         <zip>01701</zip>
      </address>
      <address>
         <street>720 Prospect</street>
         <city>Framingham</city>
         <state>MA</state>
         <zip>01701</zip>
      </address>
      <address>
         <street>120 Ridge</street>
         <state>MA</state>
         <zip>01760</zip>
      </address>
   </customer>
</customers>

But sometimes the XML data will come as follows and this would cause an exception in the program because the expected root is different.

<?xml version="1.0" encoding="UTF-8"?>
<data>
   <customers>
      <customer id="55000">
         <name>Charter Group</name>
         <address>
            <street>100 Main</street>
            <city>Framingham</city>
            <state>MA</state>
            <zip>01701</zip>
         </address>
         <address>
            <street>720 Prospect</street>
            <city>Framingham</city>
            <state>MA</state>
            <zip>01701</zip>
         </address>
         <address>
            <street>120 Ridge</street>
            <state>MA</state>
            <zip>01760</zip>
         </address>
      </customer>
   </customers>
</data>

One way I am thinking is to read the XML, check for the data root, remove it and start processing from this new data.

Is there any way I could set XmlSerializer to look for the customers element and take that as the root when deserializing the XML?


Solution

  • this code works for both xmls

        xml=xml.Replace("\r\n<data>","").Replace("\r\n</data>","");
    
        XmlDocument xmlDoc = new XmlDocument();
        xmlDoc.LoadXml(xml1);
        var node = xmlDoc.SelectNodes("customers");
    

    or using XDocument

      var xDoc = XDocument.Parse(xml);
    
        var paymentRecord = xDoc.Element("data");
        if (paymentRecord != null)
        {
            var nodes = xDoc.Element("data").Elements();
            paymentRecord.Remove();
            xDoc.Add(nodes);
        }