如何解析xml到hashmap? [英] how to parse xml to hashmap?
问题描述
我有一个我要解析的xml示例
I have an example of an xml I want to parse
<?xml version="1.0" encoding="utf-8"?>
<Details>
<detail-a>
<detail> attribute 1 of detail a </detail>
<detail> attribute 2 of detail a </detail>
<detail> attribute 3 of detail a </detail>
</detail-a>
<detail-b>
<detail> attribute 1 of detail b </detail>
<detail> attribute 2 of detail b </detail>
</detail-b>
</Details>
我想从这个xml编写一个方法,将其解析为hashmap,键是一个字符串和值是一个字符串列表。
I would like from this xml to write a method that will parse it to hashmap that the key is a string and the value is a list of strings.
例如:keydetail avalue = {detail 1 of detail a,attribute 2 of detail a ,属性3详细信息为}
for instance : key "detail a" value={"attribute 1 of detail a","attribute 2 of detail a","attribute 3 of detail a"}
等等..
最佳方式是什么去做这个 ?因为我感到困惑:\
what is the best way to do this ? because I got confused :\
我到目前为止试图打印细节-a和细节-b但我得空白......
I got this far to try to print detail-a and detail-b but I get blank...
public static void main(String[] args) {
// TODO Auto-generated method stub
DocumentBuilderFactory factory=DocumentBuilderFactory.newInstance();
DocumentBuilder builder;
try {
builder = factory.newDocumentBuilder();
File f= new File("src/Details.xml");
Document doc=builder.parse(f);
Element root=doc.getDocumentElement();
NodeList children=root.getChildNodes();
for(int i=0;i<children.getLength();i++)
{
Node child=children.item(i);
if (child instanceof Element)
{
Element childElement=(Element) child;
Text textNode=(Text)childElement.getFirstChild();
String text=textNode.getData().trim();
System.out.println(text);
}
}
} catch (ParserConfigurationException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (SAXException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
推荐答案
使用 JAXB
从 xml
读取并将其保存到自定义对象。
Use JAXB
to read from xml
and save it to a custom object.
自定义对象类:
import java.util.List;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlElementWrapper;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
@XmlRootElement(name = "Details")
@XmlType(propOrder = { "detailA", "detailB" })
public class Details {
private List<String> detailA;
private List<String> detailB;
public void setDetailA(List<String> detailA) {
this.detailA = detailA;
}
@XmlElementWrapper(name = "detail-a")
@XmlElement(name = "detail")
public List<String> getDetailA() {
return detailA;
}
public void setDetailB(List<String> detailB) {
this.detailB = detailB;
}
@XmlElementWrapper(name = "detail-b")
@XmlElement(name = "detail")
public List<String> getDetailB() {
return detailB;
}
}
将xml中的数据提取到对象中,然后根据需要将内容添加到地图:
Extract the data from your xml into the object, then add contents to a map as desired:
public static void main(String[] args) throws JAXBException, FileNotFoundException {
System.out.println("Output from our XML File: ");
JAXBContext context = JAXBContext.newInstance(Details.class);
Unmarshaller um = context.createUnmarshaller();
Details details = (Details)um.unmarshal(new FileReader("details.xml"));
List<String> detailA = details.getDetailA();
List<String> detailB = details.getDetailB();
Map<String, String[]> map = new HashMap<String, String[]>();
map.put("detail-a", detailA.toArray(new String[detailA.size()]));
map.put("detail-b", detailB.toArray(new String[detailB.size()]));
for (Map.Entry<String, String[]> entry : map.entrySet()) {
//key "detail a" value={"attribute 1 of detail a","attribute 2 of detail a","attribute 3 of detail a"}
System.out.print("Key \"" +entry.getKey()+"\" value={");
for(int i=0;i<entry.getValue().length;i++){
if(i!=entry.getValue().length-1){
System.out.print("\""+entry.getValue()[i]+"\",");
}
else{
System.out.print("\""+entry.getValue()[i]+"\"}");
}
}
System.out.println();
}
}
输出将是:
Output from our XML File:
Key "detail-a" value={"attribute 1 of detail a","attribute 2 of detail a","attribute 3 of detail a"}
Key "detail-b" value={"attribute 1 of detail b","attribute 2 of detail b"}
作为备注:如果您需要添加更多详细信息,例如 detail-c $ c $,这仅适用于您在问题中提供的xml。 c>等等,你也必须在你的自定义对象中定义它们。
As a note: this will work only for the xml you provided as input in your question, if you need to add more details like detail-c
and so on you must define them in your custom object as well.
使用的XML:
<?xml version="1.0" encoding="utf-8"?>
<Details>
<detail-a>
<detail>attribute 1 of detail a</detail>
<detail>attribute 2 of detail a</detail>
<detail>attribute 3 of detail a</detail>
</detail-a>
<detail-b>
<detail>attribute 1 of detail b</detail>
<detail>attribute 2 of detail b</detail>
</detail-b>
</Details>
这篇关于如何解析xml到hashmap?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!