正确读取xml,但订单稍后会搞乱

时间:2016-06-21 14:02:45

标签: c# xml

我将文件中的xml数据解析为此类的对象列表:

public class VerificationSample
{
    public double DesiredA { get; set; }
    public double DesiredB { get; set; }
    public double DesiredC { get; set; }

    // ..

    public void ReadXml(XmlReader reader)
    {
        reader.ReadToFollowing("VerificationSample");

        this.DesiredA = (double)FileStructure.GetAttributeSafe(reader, "DesiredA", typeof(double));
        this.DesiredB = (double)FileStructure.GetAttributeSafe(reader, "DesiredB", typeof(double));
        this.DesiredC = (double)FileStructure.GetAttributeSafe(reader, "DesiredC", typeof(double));
        this.ReferenceNumber = (int)FileStructure.GetAttributeSafe(reader, "ReferenceNumber", typeof(int));
        // ..
    }
}

我读了这个样本xml:

  <VerificationSamples Count="4">
    <VerificationSample DesiredA="0.000" DesiredB="50.000" DesiredC="0.000" ReferenceNumber="0"/>
    <VerificationSample DesiredA="75.000" DesiredB="-3.000" DesiredC="0.000" ReferenceNumber="0"/>
    <VerificationSample DesiredA="-30.000" DesiredB="0.000" DesiredC="0.000" ReferenceNumber="1"/>
    <VerificationSample DesiredA="-2.000" DesiredB="-60.000" DesiredC="0.200" ReferenceNumber="1"/>
  </VerificationSamples>

使用此例程:

public void LoadFromFile(string path)
{
    XmlReader reader = XmlReader.Create(path);

    // ..

    reader.ReadToFollowing("VerificationSamples");
    int count = (int)FileStructure.GetAttributeSafe(reader, "Count", typeof(int));
    this.VerificationSamples.Clear();

    for (int i = 0; i < count; i++)
    {
        VerificationSample newVerificationSample = new VerificationSample();
        newVerificationSample.ReadXml(reader);
        this.VerificationSamples.Add(newVerificationSample);
    }
}

到目前为止一切都很好,并且像魅力一样。但是,稍后当我执行另一个函数,我尝试访问我的VerificationSamples列表以使用我的对象的某些值时,对象的顺序变得混乱..所以xml中的第一行(是第一个对象)但是以后它是第3个。第2个是第1个。第4个是第2个等等(没有明显的模式)。有谁想象为什么???

3 个答案:

答案 0 :(得分:1)

如果文件不大,请使用XElement。

using System.Xml.Linq  
XElement file=XElement.Load(@"your path");  
foreach(var VerificationSample in file.Elements("VerificationSample"))   
{  
   // do want you want XElement type VerificationSample in order at the file  
}

答案 1 :(得分:1)

this answerList<T>保证插入顺序和检索顺序。

如果物品没有按照添加顺序排出,则会有一些外力破坏顺序(可能是排序)。

答案 2 :(得分:1)

由于从数据库中检索数据时出现问题,因此发生了这种情况。现在通过在xml OrderID中添加一个属性来修复它,该属性将用作订单的参考:

  <VerificationSamples Count="4">
    <VerificationSample DesiredA="0.000" DesiredB="50.000" DesiredC="0.000" ReferenceNumber="0" OrderID="1"/>
    <VerificationSample DesiredA="75.000" DesiredB="-3.000" DesiredC="0.000" ReferenceNumber="0" OrderID="2"/>
    <VerificationSample DesiredA="-30.000" DesiredB="0.000" DesiredC="0.000" ReferenceNumber="1" OrderID="3"/>
    <VerificationSample DesiredA="-2.000" DesiredB="-60.000" DesiredC="0.200" ReferenceNumber="1" OrderID="4"/>
  </VerificationSamples>

无论何时我从数据库中检索列表,我只需按OrderID对其进行排序。 VerificationSamples.OrderBy(x => x.OrderID);