将xml数据解析为Vector3

时间:2014-10-22 15:44:53

标签: c# xml parsing

我在C#编码。 我有一个包含不同点的xml文件。

xml文件包含三个不同的部分。第一部分包含顶点,第二部分包含正常,最后一部分包含索引。

我想知道如何解析xml文件并存储这些值。我的问题是将其转换为Vector3类型。

这是文件的样子:

93.74445056915283,-1.859979498507132,2.36335901389315,
93.74445056915283,-1.939160544096572,2.368864585972887,93.74445056915283,
-1.781553864479065,3.202673300504684,93.74445056915283,-1.781567934571608,
2.36155147915304,93.74445056915283,-0.9234275662899016,3.202673300504684,
93.74445056915283,-1.623975274812637,2.368862884104112,93.74445056915283,
-1.703156483525081,2.363355632934579,93.74445056915283,-1.544259938449322,

2 个答案:

答案 0 :(得分:0)

您的示例看起来更像是由逗号分隔的十进制数。 我还假设您指的是Unity

中的Vector3

此示例返回Vector3的列表。

var inputString = "93.74445056915283,-1.859979498507132,2.36335901389315, 93.74445056915283,-1.939160544096572,2.368864585972887, 93.74445056915283,-1.781553864479065,3.202673300504684, 93.74445056915283,-1.781567934571608,2.36155147915304, 93.74445056915283,-0.9234275662899016,3.202673300504684, 93.74445056915283,-1.623975274812637,2.368862884104112, 93.74445056915283,-1.703156483525081,2.363355632934579, 93.74445056915283,-1.544259938449322,2.378187850255953";
var coordinates = inputString.Split(',').Select(n => float.Parse(n, CultureInfo.InvariantCulture.NumberFormat)).ToList();

var myVectors = new List<Vector3>();
for(var i=0;i<coordinates.Count;i+=3)
{
    var myVector = new Vector3(coordinates[i], coordinates[i+1], coordinates[i+2]);
    myVectors.Add(myVector);
}

我只是从头开始编写这段代码,所以可能无法编译。 还要注意我假设所有数字都可解析为浮点数(没有特殊字符,您的语言环境&#39;小数点是点.)。我也假设输入数字正确。由于Vector3在构造函数中需要3个数字,因此必须将其计数为3。

答案 1 :(得分:0)

以下是我想要实现的内容的片段。

  using (XmlReader reader = XmlReader.Create("generator_0000001.xml"))
  {
     List<Vector3> verticesList = new List<Vector3>();
     while (reader.Read())
     {
         if (reader.IsStartElement())
         {
            switch (reader.Name)
            {
              case "Real64List":
              if (reader.Read())
              {
                float vertices = Convert.ToInt64(reader.Value.Trim());
                Vector3 oVert = new Vector3(vertices);
                verticesList.Add(oVert);
              }
              break;
            }
         }
      }

我正在尝试解析的文件如下所示: 93.74445056915283,-1.859979498507132,2.36335901389315, 93.74445056915283,-1.939160544096572,2.368864585972887, 93.74445056915283,-1.781553864479065,3.202673300504684, 93.74445056915283,-1.781567934571608,2.36155147915304, 93.74445056915283,-0.9234275662899016,3.202673300504684, 93.74445056915283,-1.623975274812637,2.368862884104112, 93.74445056915283,-1.703156483525081,2.363355632934579, 93.74445056915283,-1.544259938449322,2.378187850255953 .....