2012-03-20 52 views
1

我想向xml定義文件中添加屬性根據xml文件中屬性的更改更新java類中的數據

現在我希望將此更改反映到java類中。你能建議如何做到這一點。另外我想添加這個屬性作爲一個數據成員在它的一個java類中的getter和setter。我已經完成了。我想知道如何將xml的節點中的值分配給此類中的java屬性。請只告訴我邏輯。

+0

讀取屬性值只是爲了澄清:你想改變*源代碼*或*編譯的類文件*?我不清楚這一點。 – 2012-03-20 05:13:21

+0

Andreas我只是將xml的節點中的值分配給java屬性的邏輯,將其分配給方法 public void init(Node node)。你能幫我解決這個問題嗎?請注意,java類的成員與xml文件中的屬性同步。所以請告訴我如何將節點中的值分配給java類中的相應屬性。 – user1280041 2012-03-20 05:29:35

+0

基本上有一個xsd文件。我想添加一個屬性到這個xsd文件。現在這個改變應該反映在一個java類dataservices.DataServicesLayout.java中,添加如下的新常量: - public static final String SERVICE ID =「serviceId」。第二個目標是在另一個java類中添加屬性private String serviceId以及getter和setter方法。然後,我們需要將xml文件的節點中的值分配給java屬性,方法是public void init(節點節點) – user1280041 2012-03-20 06:19:53

回答

1

由於您已經有了用於XML文件的模式,並且您希望數據類型爲Java類,請考慮使用JAXB。這個XML綁定API可以自動生成模式中的類,它提供了編組和解組XML文檔的方便方法。 (IAW:「轉換一個XML到Java實例,反之亦然)

+0

我只是希望邏輯將xml的節點中的值分配給java屬性,轉換爲方法 。我整理的其他要求。你能幫助這方面嗎? – user1280041 2012-03-20 07:09:06

+0

沒有簡單的「邏輯」。如果您想自動執行此操作,請使用JAXB或最初自動生成類的框架,然後重新運行自動生成。如果你想手工完成 - 分析模式,然後分析源文件,最後是綁定規則/邏輯,然後編寫字段和方法。 – 2012-03-20 07:18:33

0

嘗試執行使用此代碼

您attribute.xml

<attributes> 
    <attribute-list> 
      <attribute> 
       <fname>riddhish</fname> 
      <lname>chaudhari</lname> 
     </attribute> 
    </attribute-list> 
<attributes> 

類文件

public static final String ATTRIBUTE_LIST = "ATTRIBUTE_LIST"; 
public static final String ATTRIBUTE = "ATTRIBUTE"; 
public static final String FNAME = "FNAME"; 

代碼。從XML文件中提取屬性

Document document = null; 
NodeList nodeList = null; 
Node node = null; 

nodeList = document.getElementsByTagName("----file attributes.xml---").item(0).getChildNodes(); 
HashMap <String,Object> localParameterMap = new HashMap<String,Object>(); 

for(int i=0; i<nodeList.getLength(); i++){ 
    node = nodeList.item(i); 
    if(node.getNodeName().equals("attribute-list")){ 
     Collection objCollection = readAttributeList(node); 
     localParameterMap.put(ATTRIBUTE_LIST, objCollection); 
    } 
} 

()函數readAttributeList

private Collection readAttributeList(Node node){ 
    Collection<Object> objCollection = new ArrayList<Object>(); 
    NodeList nodeList = node.getChildNodes(); 

    for(int i=0; i < nodeList.getLength(); i++){ 
     Node subNode = nodeList.item(i); 

     if(subNode.getNodeName().equals("attribute")){ 
      NodeList attributeList = subNode.getChildNodes(); 
      HashMap <String,Object> attributeMap = new HashMap<String,Object>(); 

       for(int j=0; j<attributeList.getLength(); j++){ 
        Node attributeNode = attributeList.item(j); 

        if(attributeNode.getNodeName().equals("fname")){ 
         attributeMap.put(FNAME, attributeNode.getTextContent().trim()); 
        } 
       } 
     } 
     objCollection.add(attributeMap); 
    } 
    return objCollection; 
} 

在可變

String strfname = null; 

if(map.get(CLASS_NAME.FNAME) != null) { 
    strfname = (String)map.get(CLASS_NAME.FNAME); 
} 
+0

非常感謝Riddhish – user1280041 2012-03-21 04:23:25