Colm Clarke
Colm Clarke

Reputation: 490

Parsing xml into a dictionary

I am trying to parse an XML file into a dictionary . The problem is all the solutions i find online show how to do this by searching the name element. my applications name element itself is what i want to search.

<?xml version="1.0" encoding="UTF-8"?>
    <calibration>
      <ZoomLevel 250="0.0100502512562814" />
      <ZoomLevel 251="0.0100502512562814" />
      <ZoomLevel 252="0.0100502512562814" />
      <ZoomLevel 253="0.0100502512562814" />
      <ZoomLevel 254="0.0100502512562814" />
      <ZoomLevel 255="0.0100502512562814" />
      <ZoomLevel 256="0.0100502512562814" />
      <ZoomLevel 257="0.0100502512562814" />
</calibration>

I am looking to remove the key"250, 251 etc" and the value and create a dictionary.

Sorry if this is a stupid ask but im new to c# and im struggling allot with this

Upvotes: 0

Views: 186

Answers (1)

MarcinJuraszek
MarcinJuraszek

Reputation: 125630

Unfortunately, your XML is not a valid one. Attribute name cannot start from digit.

But to show how it could be done when XML is valid let's pretend it looks like that:

<?xml version="1.0" encoding="UTF-8"?>
    <calibration>
      <ZoomLevel _250="0.0100502512562814" />
      <ZoomLevel _251="0.0100502512562814" />
      <ZoomLevel _252="0.0100502512562814" />
      <ZoomLevel _253="0.0100502512562814" />
      <ZoomLevel _254="0.0100502512562814" />
      <ZoomLevel _255="0.0100502512562814" />
      <ZoomLevel _256="0.0100502512562814" />
      <ZoomLevel _257="0.0100502512562814" />
</calibration>

Notice _ before each attribute name. You can get Dictionary<int, decimal> using following LINQ to XML query:

var xDoc = XDocument.Load("Input.txt");

var dict = xDoc.Root.Elements("ZoomLevel")
                    .Select(x => x.Attributes().First())
                    .ToDictionary(a => int.Parse(a.Name.LocalName.Substring(1)), a => (decimal)a);

a.Name.LocalName.Substring(1) skips the first characted - _ - from attribute name.

Upvotes: 3

Related Questions