Interview patterns - technical interview questions logo
 

XML Parsing questions

by Alex 12. October 2009 12:48

Moving out of product team into research world dramatically shorten the amout of interview I conduct. The matter of fact, is that I didn't do a single interview for the last couple months. So, here is the question one of my friends shared with me after his interview for Web Developer position:

Write a function to remove duplicate entries for any given XML. The node considered a duplicate, then provided "key" field is a duplicate.

Example:

<Products>
   
<Product>
     <Name>Milk</Name>
     <Amount>4</Amount>
   </Product>
   <Product>
     <Name>Milk</Name>
     <Amount>0.5</Amount>
   </Product>
   <Product>
     <Name>Coffe</Name>
     <Amount>0.5</Amount>
   </Product>
</Products>

Based on the "Name" field, node 1 and 2 considered duplicated, but based on "Amount" field nodes 2 and 3 are duplicates. So, the task is to write a function:

string DeDup(string xml, string keyNode, string rootPath)

Possible solution:

private static string RemoveDuplicates(string xml, string key, string rootXPath)
{
XmlDocument doc = new XmlDocument();
List sb = new List();
string keyValue;
try
{
doc.Load(xml);
XmlElement root = doc.DocumentElement;
XmlNodeList xnodelist = root.SelectNodes(rootXPath);
int i=0;
foreach (XmlNode item in xnodelist)
{
Console.WriteLine(i + "\b\b\b\b\b");
i++;
keyValue = item.SelectSingleNode(key).InnerXml;
if (sb.Contains(keyValue))
xnode.RemoveChild(item);
else
sb.Add(keyValue); 
}
return doc.OuterXml;
}
catch (Exception ex)
{
// Log exception... 
throw ex;
}
}
This solution while works well for small xml file, is not a good fit for de-duping large XMLs.So, the bonus question will be to utilize SAX parser in C# to remove duplicates in large XML files...

Currently rated 4.5 by 2 people

  • Currently 4.5/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Tags: , , , ,

C# | Interview Questions | On-Site Interview Strategies


Comments




All material copyright © North Pacific Technology Group, LLC. All rights are reserved. No part of any material on this web site may be reproduced, or stored in a database or retrieval system, distributed, or transmitted in any form or by any means, electronic, mechanical, photocopying, recording, or otherwise, without the prior written permission. Terms of use.

Powered by BlogEngine.NET 1.4.5.0

Job Search

what
job title, keywords
where
city, state, zip
jobs by job search