Link to home
Start Free TrialLog in
Avatar of angireddy
angireddy

asked on

XML Data in to Structure

I have an xml file and want to read the xml in to array of structure, for example

xml file looks like this:-
<MarkupItems>
 <items>
   </TagValue>
   </TagID>
   <InputOffset>
      </OffsetValue>
      </OffsetLength>
   </InputOffset>
   <OutputOffset>
      </OffsetValue>
      </OffsetLength>
   </OutputOffset>
 </items>
 <items>
   </TagValue>
   </TagID>
   <InputOffset>
      </OffsetValue>
      </OffsetLength>
   </InputOffset>
   <OutputOffset>
      </OffsetValue>
      </OffsetLength>
   </OutputOffset>
  </items>
</MarkupItems>

my structure looks like this:-
public struct Offset
{
      public ulong OffsetValue;
      public ulong OffsetLength;
}
public struct TagItem
{
      public Offset InputOffset;
      public Offset OutputOffset;
      public string TagValue;
      public string TagID;
}
public struct MarkUpItems
{
           TagItem[] _items;
}

now i want to read the xml file in to the markupitems structure.
ASKER CERTIFIED SOLUTION
Avatar of Razzie_
Razzie_

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of angireddy
angireddy

ASKER

Hello Mr.Razzie,

its saying Object Reference not set to an instance of an object for the line

inputOffset.OffsetValue = Convert.ToUInt64(itemNodes[i].SelectSingleNode("InputOffset/OffsetValue").InnerText);

Reddy
That is correct. As I stated in my post, there is no error checking for correct input. You'd have to check if the Nodes aren't empty before converting them to a long valuetype. (if ......InnerText != String.Empty) or something, etc :)
Hi,

how to write back the marupItems back to the xml file using the same example as above.

thanking you
reddy
The correct way to do this would be by rebuilding the XmlDocument. The complete code is a lot of work but below is how it is done. Just fill in the missing data:

---------------------------------------------------------------------------------------------
// Create all the nodes
XmlElement xmlElementRoot = xmlDoc.CreateElement("MarkUpItems");
XmlElement xmlElementItems = xmlDoc.CreateElement("items");
....
XmlElement xmlElementOL = xmlDoc.CreateElement("OffsetLength");

// Create the text for the nodes. Obtain the data from the struct.
XmlText xmlTextOL = xmlDoc.CreateTextNode(tagItem.OutputOffset.OffsetLength);
....
etc

// Append the text elements to the nodes
xmlElementOL .AppendChild(xmlTextOL);
...
etc

// Connect the nodes to eachother. Start with root node, its childeren, THEIR childeren, etc.
xmlDoc.AppendChild(xmlElementRoot);
xmlElementRoot.AppendChild(xmlElementItems);
xmlElementItems.AppendChild(xmlElementOutputOffset);
...
etc

----------------------------------------------------------------------

Use a foreach loop like foreach(TagItem t in markUpItems._items) to get all items nodes.