update data in java class as per change in attribute in the xml file

后端 未结 2 1715
说谎
说谎 2020-12-21 22:36

I want to add an attribute to the xml defination file

Now i want this change to be reflected in a java class . Can you suggest as to how it can be done . Also i w

相关标签:
2条回答
  • 2020-12-21 22:57

    As you already have a schema for your xml files and you want java classes for the data types, consider using JAXB. This xml binding API can autogenerate classes from schemas and it provides convenient methods to marshal and unmarschal XML documents. (IAW: "convert an XML into java instances and vice versa).

    0 讨论(0)
  • 2020-12-21 23:00

    Try to implement using this code

    your attribute.xml

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

    Class File

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

    Code for rading attributes from xml file

    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);
        }
    }
    

    function() 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;
    }
    

    for reading attribute values in variable

    String strfname = null;
    
    if(map.get(CLASS_NAME.FNAME) != null) {
        strfname = (String)map.get(CLASS_NAME.FNAME);
    }
    
    0 讨论(0)
提交回复
热议问题