我已经被解析,需要下面的XML文档:最佳方式属性
...
<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>
...
我写了下面的代码解析:
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);
}
的代码抛出一个NullReferenceException如果我尝试获取不存在的certian属性的值(IE:tNode.Attribute.GetNamedItem(“repeat”)。值在所有没有repeat属性的节点上失败)。什么是我可以验证某个属性是否存在的方法?
此外上面的代码根本不干净。组织上述代码的最佳方式是什么?
编辑:我知道的方法,您可以单独检查属性是否为null或不从它们的值之前,但这使得代码看起来非常肮脏,因为我需要写很多ifs(或嵌套的ifs)
if (tNode.Attributes.GetNamedItem("decimal") != null)
if (tNode.Attributes.GetNamedItem("decimal").Value == "true")
convert_decimal = true;
从长远来看,如果我必须编写更多的属性,这会变得有问题。我想知道更多的这种有组织的方法(可能XML属性可以枚举?我不知道。)
竖起大拇指为我的要求和写一个示例代码。如果有多个使用相同属性的根,是否有合适的说法[XmlRoot(“tx”)],[XmlRoot(“rx”)]表示可以在执行任何一个根时引用同一个类反序列化? – l46kok 2012-07-20 05:28:18