如何将XML文本(而非属性)读入float?

时间:2011-01-27 14:12:26

标签: c# xml linq linq-to-xml

嘿伙计们我试图从C#中的XML文件中读取3D点(X,Y,Z)(所有Float)。

用于格式化的每个点的XML如下:

<Point X="-4865.764" Y="-4945.29" Z="261.1602"/>

我可以用以下内容阅读:

return new XElement("Point", new XAttribute("X", X), new XAttribute("Y", Y), new XAttribute("Z", Z));

但现在我必须从XML格式中读取我的观点:

<Point>679.7905 -4312.875 60.93259</Point> 

如上所示格式化时,如何将XML读入我的浮点变量(X,Y和Z)?

非常感谢,

杰西

1 个答案:

答案 0 :(得分:2)

您需要拆分该值,例如

string[] values = element.Value.Split(' ');
// Possibly do validation here to check there are 3 values?
// Note the specification of the culture here - otherwise if you're in a culture
// which uses "," as the decimal separator, it won't do what you want...
float x = float.Parse(values[0], CultureInfo.InvariantCulture);
float y = float.Parse(values[1], CultureInfo.InvariantCulture);
float z = float.Parse(values[2], CultureInfo.InvariantCulture);