问题
I am trying to populate a xml file from user's input values. User will give 2 entries a Key and a value. And i have a model class which is a as below:
public class Person
{ private HashMap<String, String> hash = new HashMap<String, String>();
public Person()
{ }
public Person(String key, String val)
{ hash.put(key, val); }
public String GetFirstName(String k)
{ return hash.get(k); }
}
How to make a xml from this object of the class? and how to retrieve a value from xml against a key?
And i want the xml like this:
<AllEntries>
<entry key="key1">value1</entry>
<entry key="key2">value2</entry>
<entry key="key3">value3</entry>
</AllEntries>
回答1:
You need to use a XML parser like Java DOM or SAX. The example below is Java DOM and shows you how to loop through the HashMap
and add your entries to your_xml.xml
.
File xmlFile = new File("your_xml.xml");
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(xmlFile);
for (Map.Entry<String, String> m : hash.entrySet()) {
// Create your entry element and set it's value
Element entry = doc.createElement("entry");
entry.setTextContent(m.getValue());
// Create an attribute, set it's value and add the attribute to your entry
Attr attr = doc.createAttribute("key");
attr.setValue(m.getKey());
entry.setAttributeNode(attr);
// Append your entry to the root element
doc.getDocumentElement().appendChild(entry);
}
Then you just need to save your document over the original file. Once your Document
has been edited you'll probably want to convert it to a String to parse to your OutputStream
of choice for saving.
来源:https://stackoverflow.com/questions/22553473/how-am-i-going-to-create-a-xml-file-using-pullparser-for-hashmap