【问题标题】:Reasonable method to store and read constant values存储和读取常量值的合理方法
【发布时间】:2013-06-14 21:20:52
【问题描述】:

所以我有一个xml结构,格式如下:

< Smart>
  < Attribute>
    < id >1 </id >
    < name >name </ name>
    < description >description</ description >
  </ Attribute>
     .
     .
     .
</Smart>

然后我需要获取用户输入来生成数据表,这取决于用户输入的内容,将使用不同的常量。 ID 用于区分不同的常量。所有这些常量都是在启动之前预定义的。以下是我查找所需常量并将它们存储到数据表中的代码

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++;
}
}

这确实有助于在相应的行中找到所需的常量。然而,似乎很多工作却没有多少收获。使用数据集之类的东西可能会做得更好吗?任何其他建议都会非常有帮助。

【问题讨论】:

    标签: c# xml constants


    【解决方案1】:

    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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-05-13
      • 2016-03-20
      • 1970-01-01
      • 2015-01-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多