How am I going to create a xml file using pullparser for hashmap

不想你离开。 提交于 2019-12-02 18:26:13

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!