C# 存储和读取常量值的合理方法
因此,我有一个xml结构,格式如下:C# 存储和读取常量值的合理方法,c#,xml,constants,C#,Xml,Constants,因此,我有一个xml结构,格式如下: < Smart> < Attribute> < id >1 </id > < name >name </ name> < description >description</ description > </ Attribute> . . . </Smart> 1 name
< Smart>
< Attribute>
< id >1 </id >
< name >name </ name>
< description >description</ description >
</ Attribute>
.
.
.
</Smart>
1
name
description
.
.
.
然后,我需要获得用户输入以生成数据表,这取决于用户输入的内容,将使用不同的常量。ID用于区分不同的常数。所有这些常量都是在启动前预定义的。下面是我查找所需常量并将其存储到datatable中的代码
for ( int row = 0; row < rowcount; row++)
{
found = false;
XmlTextReader textReader = new XmlTextReader ("Smart_Attributes.xml" );
textReader.ReadStartElement( "Smart" );
while (!found)
{
textReader.ReadStartElement("Attribute" );
DataId = Convert .ToByte(textReader.ReadElementString("id" ));
if (DataId > id)
{
dataView[count][5] = "Unknown" ;
dataView[count][7] = "Unknown" ;
found = true ;
}
if (DataId == id)
{
dataView[count][5] = textReader.ReadElementString("name" );
dataView[count][7] = textReader.ReadElementString("description" );
found = true ;
}
else
{
textReader.ReadElementString("name" );
textReader.ReadElementString("description" );
}
textReader.ReadEndElement(); //</Attribute>
}
count++;
}
}
for(int row=0;rowid)
{
数据视图[计数][5]=“未知”;
数据视图[计数][7]=“未知”;
发现=真;
}
if(DataId==id)
{
dataView[count][5]=textReader.ReadElementString(“名称”);
dataView[count][7]=textReader.ReadElementString(“说明”);
发现=真;
}
其他的
{
textReader.ReadElementString(“名称”);
textReader.ReadElementString(“说明”);
}
textReader.ReadEndElement();//
}
计数++;
}
}
这确实有助于为相应的行找到所需的常量。然而,这似乎是一个没有多少收获的工作很多。使用诸如数据集之类的工具是否可以做得更好?任何其他建议都会非常有用。XmlTextReader的好处在于其仅向前的特性。这允许您在一次扫描中读取非常大的文件。如果您的XML文件较小,并且您愿意随时将整个结构保存在内存中,那么可以使用Linq2Xml,并将其读入
XDocument
类
var doc = XDocument.Load("Smart_Attributes.xml");
var rows = doc.Descendants("Attribute").Where(e => e.Element("id").Value == id)
.Select(e => new
{
Name = e.Element("name").Value,
Description = e.Element("description").Value
});
// Load rows into your datatable