# Parsing XML in C# .NET [closed]

I am working on a way to parse data using xml.

The file that I am given contains lines that look like this:

George | Washington | Carver


or someone else can send me someting like this

Carver | Washington | George


And so on...

No matter what the format is, whoever sends me the file will also send me rules on how to parse the file. In the first example, it's First Name | Middle Name | Last Name. And in the second example, it's Last Name | Middle Name | First Name

Instead of writing a special case for each possibility, I created an XML file to describe the meta data.

<file>
<first>0</first>
<middle>1</middle>
<last>2</last>
</file>


For instance, in this case. The tag first corresponds to 0 indicating that first name occurs at the 0th position.

Intuitively, I thought about creating a dictionary, with the key set to be the tag, and the value to be the text. Like such...

    public static IDictionary<string, string> GetLookupTable(string xmlContents)
{
XElement xmlElement = XElement.Parse(xmlContents);

IDictionary<string, string> table = new Dictionary<string, string>();

foreach (var element in xmlElement.Elements())
{
}

return table;
}


However, I'm not really familiar with .NET implementation of things, which led me to question some stuff.

1. Would it be better to just traverse XElement instead of creating a dictionary? I don't think this is a good idea since I believe that XElement traversal may invovle an unordered tree traversal to get what I need. Doing this for each property (I have more than just 3) would be very inefficient. I am just speculating here...

2. Is retrieval from dictionary constant time? I know that in Java HashMap has constant get. If that was the case for c# as well, then this would seem like a better route to go as I would just traverse once, and then be able to retrieve whatever I need in constant time.

• If you're not going to need to configure anything else, then I think XML is an overkill. A simple text file containing 0 1 2 would suffice. – svick Jun 13 '13 at 21:14
• As an entirely different route, you might want to look at this FlatFileParser project. It can read the |-separated data in directly, with appropriate column names, and stick it into a DataTable. – Bobson Jun 13 '13 at 21:23

You can use the order of XML nodes as field order:

<importformat>
<firstname/>
<middlename/>
<lastname/>
</importformat>


and parse it like that:

public static string[] GetFieldsOrder(string xmlContents)
{
return XElement.Parse(xmlContents)
.Elements()
.Select(element => element.Name.LocalName)
.ToArray();
}