2011-01-07 81 views
1

在ActionScript 3中,如何從xml解碼爲ActionScript類?在ActionScript 3中,如何從xml解碼爲ActionScript類?

我可以通過使用XmlEncoder從ActionScript類到xml進行編碼。

我當時使用的xml模式是這樣的。使用POJO(User.java),無註釋

[schema1.xsd]

<?xml version="1.0" encoding="UTF-8" standalone="yes"?> 
<xs:schema version="1.0" xmlns:xs="http://www.w3.org/2001/XMLSchema"> 
    <xs:complexType name="user"> 
    <xs:sequence> 
     <xs:element name="id" type="xs:string" minOccurs="0"/> 
     <xs:element name="password" type="xs:string" minOccurs="0"/> 
     <xs:element name="userDate" type="xs:dateTime" minOccurs="0"/> 
    </xs:sequence> 
    </xs:complexType> 
</xs:schema> 

這個模式是通過螞蟻創建(schemagen)任務。

但我無法通過使用此架構和XmlDecoder從xml解碼爲ActionScript類。 (無論如何,我無法從Object類型轉換爲User類型。)

我不希望在Java類中放置任何類似@XmlRootElement或@XmlType的註釋。

但是,我需要一個用於ActionScript的客戶端模式文件來編組和解組。

請告訴我任何解決方案或實例...

回答

0

下面的類:

import java.util.Date; 

public class User { 

    private String id; 
    private String password; 
    private Date userDate; 

    public String getId() { 
     return id; 
    } 

    public void setId(String id) { 
     this.id = id; 
    } 

    public String getPassword() { 
     return password; 
    } 

    public void setPassword(String password) { 
     this.password = password; 
    } 

    public Date getUserDate() { 
     return userDate; 
    } 

    public void setUserDate(Date userDate) { 
     this.userDate = userDate; 
    } 

} 

可以用來解組下面的XML:

<?xml version="1.0" encoding="UTF-8"?> 
<root> 
    <id>123</id> 
    <password>foo</password> 
    <userDate>2011-01-07T09:15:00</userDate> 
</root> 

使用下面的代碼,而無需需要用戶類別的任何註釋:

import javax.xml.bind.JAXBContext; 
import javax.xml.bind.JAXBElement; 
import javax.xml.bind.Unmarshaller; 
import javax.xml.transform.stream.StreamSource; 

public class Demo { 

    public static void main(String[] args) throws Exception { 
     JAXBContext jc = JAXBContext.newInstance(User.class); 

     StreamSource source = new StreamSource("input.xml"); 
     Unmarshaller unmarshaller = jc.createUnmarshaller(); 
     JAXBElement<User> root = unmarshaller.unmarshal(source, User.class); 

     User user = root.getValue(); 
     System.out.println(user.getId()); 
     System.out.println(user.getPassword()); 
     System.out.println(user.getUserDate()); 
    } 
} 
+0

謝謝布萊斯!在Java中,我想我可以這樣寫。但如何在ActionScript 3中使用該XML編寫? – Take 2011-01-11 00:05:34