1
嗨,我試圖讀取XML持續到一個新的持續時間,但是I'T說 「無法實例類型持續時間」XML轉換期限前P0DT1H0M0S到Java
我很新的Java和Android開發。所以請保持任何nonconstructive評論自己..
代碼
import javax.xml.datatype.Duration;
Duration duration = new Duration();
嗨,我試圖讀取XML持續到一個新的持續時間,但是I'T說 「無法實例類型持續時間」XML轉換期限前P0DT1H0M0S到Java
我很新的Java和Android開發。所以請保持任何nonconstructive評論自己..
代碼
import javax.xml.datatype.Duration;
Duration duration = new Duration();
找到它自己。
try {
DatatypeFactory dtFactory = DatatypeFactory.newInstance();
} catch (DatatypeConfigurationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Duration duration = dtFactory.newDuration("p0dt1h0m0s");
編輯..
以上是不可能的,因爲一個錯誤的DatatypeFactory SOOO我建這個類來解決它自己..
public class XmlDuration {
private String _xmlDuration;
private int _years;
private int _months;
private int _days;
private int _hours;
private int _minutes;
private int _seconds;
private boolean _isNegative;
public XmlDuration(String xmlDuration) {
try {
_xmlDuration = xmlDuration;
_isNegative = ((String)_xmlDuration.subSequence(0,1)).matches("[-]");
String period;
String time;
int tIndex =_xmlDuration.indexOf("T");
period = xmlDuration.substring(0, tIndex);
time = _xmlDuration.substring(tIndex);
String numericSection = "";
for (int i = 0; i < period.length(); i++) {
char[] c = new char[] {period.charAt(i)};
String s = new String(c);
if(s.matches("\\d"))
{
numericSection += s;
}
else if (s.matches("[Yy]"))
{
_years = Integer.parseInt(numericSection);
numericSection = "";
}
else if (s.matches("[Mm]"))
{
_months = Integer.parseInt(numericSection);
numericSection = "";
}
else if (s.matches("[Dd]"))
{
_days = Integer.parseInt(numericSection);
numericSection = "";
}
}
for (int i = 0; i < time.length(); i++) {
char[] c = new char[] {time.charAt(i)};
String s = new String(c);
if(s.matches("\\d"))
{
numericSection += s;
}
else if (s.matches("[Hh]"))
{
_hours = Integer.parseInt(numericSection);
numericSection = "";
}
else if (s.matches("[Mm]"))
{
_minutes = Integer.parseInt(numericSection);
numericSection = "";
}
else if (s.matches("[Ss]"))
{
_seconds = Integer.parseInt(numericSection);
numericSection = "";
}
}
} catch (Exception e) {
// TODO: handle exception
}
}
public String getXmlString()
{
return _xmlDuration;
}
public int getYears()
{
return _years;
}
public int getMonth()
{
return _months;
}
public int getDays()
{
return _days;
}
public int getHours()
{
return _hours;
}
public int getMinutes()
{
return _minutes;
}
public int getSeconds()
{
return _seconds;
}
public boolean getIsNegative()
{
return _isNegative;
}
}
我知道這是老了......但這很棒。但是在很多情況下,需要進行比較或者至少有一致的單位。所以我認爲一個簡單的增強就是創建一個將結果總計爲秒數的方法。但要做到這一點,需要知道單位月份代表什麼。這是30天嗎?我假設一年是365天。 – 2016-01-27 12:41:39
稍遲..謝謝,但這只是標準XML持續時間的簡單轉換。它更好地使用TimeSpan或者你正在考慮的功能已經存在的東西。 – jrb 2016-06-30 12:31:58