Update data in java class by attribute change in XML file

I want to add attribute to xml protection file

Now I want this change to be reflected in the java class. Can you suggest how this can be done. I also want to add this attribute as a data member in a single java class with its getter and seters. I did it. I want to know how to assign a value from node xml to a java attribute in this class. Please tell me only the logic.

+1
source share
2 answers

Since you already have a schema for your xml files, and you need Java classes for data types, consider using JAXB . This xml binding API can automatically generate classes from schemas and provides convenient methods for marshaling and non-marshaling XML documents. (IAW: "convert XML to java instances and vice versa).

+1
source

Try to implement 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 extracting attributes from an 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; } 

to read attribute values ​​in a variable

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

All Articles