I have the following XML document that needs to be parsed:
...
<tx size_total="143">
<type size="1" start_key="02">STX</type>
<type size="3">Type</type>
<type size="3" decimal="true">Serial</type>
<type size="3" key="23 64 31">Function_Code</type>
<type size="2" decimal="true">LIU</type>
<type size="1">Status</type>
<type size="2" repeat="64" binary ="true" binary_discard="2">Value</type>
<type size="1">ETX</type>
<type size="1">LRC</type>
...
I wrote the following code for parsing:
XmlNodeList typeNodeList = txNode.SelectNodes(TYPE_NODE);
CommRuleContainer rc = new CommRuleContainer(funcNode.Attributes.GetNamedItem("name").Value,
txNode.Attributes.GetNamedItem("size_total").Value, funcNode.Attributes.GetNamedItem("id").Value);
foreach (XmlNode tNode in typeNodeList)
{
int size = Convert.ToInt32(tNode.Attributes.GetNamedItem("size").Value);
int repeat = Convert.ToInt32(tNode.Attributes.GetNamedItem("repeat").Value);
int binary_discard = Convert.ToInt32(tNode.Attributes.GetNamedItem("binary_discard").Value);
string start_key = tNode.Attributes.GetNamedItem("start_key").Value;
string key = tNode.Attributes.GetNamedItem("key").Value;
bool convert_decimal = false, convert_binary = false;
if (tNode.Attributes.GetNamedItem("decimal").Value == "true")
convert_decimal = true;
if (tNode.Attributes.GetNamedItem("binary").Value == "true")
convert_binary = true;
rc.AddTypeDefinition(tNode.Value, size, repeat, binary_discard, convert_decimal, convert_binary);
}
The code throws a nullreferenceexception if I try to obtain the value of a certian attribute that doesn’t exist (I.E: tNode.Attribute.GetNamedItem(“repeat”).value fails on all nodes that doesn’t have the repeat attribute). What is a way that I can verify if a certain attribute exists?
Also the above code isn’t clean at all. What is the best way to organize the above code?
Edit: I am aware of the approach where you can individually check whether the attributes are null or not before getting the values off them but this makes the code look very dirty as I am required to write a lot of ifs (or nested ifs)
if (tNode.Attributes.GetNamedItem("decimal") != null)
if (tNode.Attributes.GetNamedItem("decimal").Value == "true")
convert_decimal = true;
This becomes problematic in the long run if I have to write a lot more attributes. I’d like to know more of an organized approach for this (Perhaps XML Attributes can be enumerated? I don’t know.)
Agree with @nunespascal and here is the code I prepared for you already .. he answered quicker than me.. LOL:
here is my helper class for deserializing:
That should get you off to a good start. Good luck.