我试图从用户的输入值填充xml文件。用户将给出2个条目一个键和一个值。我有一个模型类,如下所示:
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); }
}
如何使一个xml从这个类的对象?如何根据键从XML检索值?
我想要这样的xml:
<AllEntries>
<entry key="key1">value1</entry>
<entry key="key2">value2</entry>
<entry key="key3">value3</entry>
</AllEntries>
您需要使用像Java DOM或SAX这样的XML解析器。下面的示例是Java DOM,它向您展示了如何遍历HashMap
并将条目添加到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);
}
然后你只需要将你的文档保存在原始文件上。一旦你的Document
被编辑,你可能会想把它转换成一个字符串来解析你的OutputStream
选择保存。