我正在尝试从用户的输入值填充 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这样的XML解析器DOM http://docs.oracle.com/javase/tutorial/jaxp/dom/readingXML.html or SAX http://docs.oracle.com/javase/tutorial/jaxp/sax/parsing.html。下面的示例是 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
已被编辑,您可能会想要将其转换为字符串 https://stackoverflow.com/questions/2567416/document-to-string解析到你的OutputStream
节省的选择。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)