我怎么创建使用pullparser为HashMap中的xml文件 [英] How am I going to create a xml file using pullparser for hashmap
问题描述
我想填充来自用户的输入值的XML文件。用户将给予2项密钥和一个值。和我有这是一个如下所示的模型类:
公共类Person
{私人的HashMap<字符串,字符串>哈希=新的HashMap<字符串,字符串>();
公众人物()
{}
公众人物(字符串键,字符串VAL)
{hash.put(键,VAL); }
公共字符串的getFirstName(字符串K)
{返回hash.get(K); }
}
如何使从这个类的对象XML?以及如何检索XML值对的关键?
,我想是这样的XML:
< AllEntries>
<输入键=键1>值1< /进入>
<输入键=键2>值2< /进入>
<输入键=KEY3>价值3< /进入>
< / AllEntries>
您需要使用XML解析器如Java的 DOM 或 SAX 。下面的例子是Java的DOM,并告诉您如何通过的HashMap
循环,并添加条目,以 your_xml.xml
。
文件XMLFILE =新的文件(your_xml.xml);
DocumentBuilderFactory的dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder的dBuilder = dbFactory.newDocumentBuilder();
文档DOC = dBuilder.parse(XMLFILE);
对于(Map.Entry的<字符串,字符串> M:hash.entrySet()){
//创建您的输入元素,并将其值
元素条目= doc.createElement(入门);
entry.setTextContent(m.getValue());
//创建一个属性,设置它的值和属性添加到您的项目
ATTR ATTR = doc.createAttribute(钥匙);
attr.setValue(m.getKey());
entry.setAttributeNode(attr)使用;
//添加你入门到根元素
。doc.getDocumentElement()的appendChild(项);
}
然后你只需要保存您的证件,原来的文件。一旦你的文件
已被编辑,你可能会想转换它把一个字符串解析你的的OutputStream
选择保存。
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>
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.
这篇关于我怎么创建使用pullparser为HashMap中的xml文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!