[英]XML - Convert Value to Specific Format
我正在將XML文件加載到GRIDVIEW中,並設法做到了。 但是我目前陷入一件事,那就是當我嘗試加載一個特定值(47.138)時。 該值應該以以下格式(Minutes:Seconds.Mileseconds)加載。 在這種情況下為“ 0:47.138”。
我的問題是,如何加載此類數據並以正確的格式顯示?
XmlNodeList drivers = doc.GetElementsByTagName("Driver");
foreach (XmlNode driver in drivers)
{
dInfo = new BusObjects.DriverInfo();
if (driver.ChildNodes[i].Name.Equals("BestLapTime"))
dInfo.FastestLap = Convert.ToDouble(driver.ChildNodes[i].InnerText).ToString("????");
}
這是我的DriverInfo.cs
private double _fastestlap;
public double FastestLap
{
get { return _fastestlap; }
set { _fastestlap = value; }
}
您可以創建一個TimeSpan
對象,並使用該對象設置文本格式。
TimeSpan ts = TimeSpan.FromSeconds(47.138);
Console.WriteLine(ts.ToString(@"mm\:ss\.fff"));
在DriverInfo
類中,您可以有一種方法可以為您執行此操作。
public string GetFormattedTime()
{
TimeSpan ts = TimeSpan.FromSeconds(_fastestlap);
return ts.ToString(@"mm\:ss\.fff");
//shorter version if you prefer
//return TimeSpan.FromSeconds(_fastestlap).ToString(@"mm\:ss\.fff");
}
MSDN具有有關自定義TimeSpan格式的更多信息。
擴展keyboardP的答案 ...。
foreach (XmlNode driver in drivers)
{
dInfo = new BusObjects.DriverInfo();
if (driver.ChildNodes[i].Name.Equals("BestLapTime"))
{
dInfo.FastestLap = Convert.ToDouble(driver.ChildNodes[i].InnerText);
}
}
// you can use an auto property for FastestLap
public double FastestLap {get; set;}
// Add another property for FormattedFastestLap:
public string FormattedFastestLap
{
get { return TimeSpan.FromSeconds(FastestLap).ToString(@"mm\:ss\.fff"); }
}
在foreach
循環中,您要設置FastestLap的值,該值是兩倍。 通過創建另一個稱為FormattedFastestLap的屬性,您可以訪問FastestLap屬性並將雙精度型轉換為字符串,方法是先轉換為TimeSpan對象,然后以格式化的字符串返回TimeSpan。
然后,在網格中,將顯示綁定到FormattedFastestLap而不是FastestLap屬性。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.