[英]how to parse xml to hashmap?
我有一个要解析的 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 键是一个字符串,值是一个字符串列表。
例如:key "detail a" value={"attribute 1 of detail a","attribute 2 of detail a","attribute 3 of detail a"}
等等..
做这个的最好方式是什么 ? 因为我很困惑:\\
我走了这么远试图打印 detail-a 和 detail-b 但我得到了空白......
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
并将其保存到自定义对象。
自定义对象类:
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 中的数据提取到对象中,然后根据需要将内容添加到地图中:
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"}
请注意:这仅适用于您在问题中作为输入提供的 xml,如果您需要添加更多详细信息,如detail-c
等,您还必须在自定义对象中定义它们。
使用的 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>
我无法抗拒使用XMLBeam提出一个更短的解决方案,该解决方案适用于任意数量的“detail-x”子元素。
public class Tetst {
@XBDocURL("resource://test.xml")
public interface Projection {
@XBRead("name()")
String getName();
@XBRead("./detail")
List<String> getDetailStrings();
@XBRead("/Details/*")
List<Projection> getDetails();
}
@Test
public void xml2Hashmap() throws IOException {
HashMap<String, List<String>> hashmap = new HashMap<String, List<String>>();
for (Projection p : new XBProjector().io().fromURLAnnotation(Projection.class).getDetails()) {
System.out.println(p.getName() + ": " + p.getDetailStrings());
hashmap.put(p.getName(), p.getDetailStrings());
}
}
}
这打印出来
detail-a: [ attribute 1 of detail a , attribute 2 of detail a , attribute 3 of detail a ]
detail-b: [ attribute 1 of detail b , attribute 2 of detail b ]
对于您的示例 test.xml 并填充一个 Hashmap。
Underscore -java库有一个静态方法 U.fromXmlMap(xmlstring)。 活生生的例子
import com.github.underscore.lodash.U;
import java.util.Map;
public class Main {
public static void main(String[] args) {
Map<String, Object> map = U.fromXmlMap(
"<Details>\r\n" +
" <detail-a>\r\n" +
"\r\n" +
" <detail> attribute 1 of detail a </detail>\r\n" +
" <detail> attribute 2 of detail a </detail>\r\n" +
" <detail> attribute 3 of detail a </detail>\r\n" +
"\r\n" +
" </detail-a>\r\n" +
"\r\n" +
" <detail-b>\r\n" +
" <detail> attribute 1 of detail b </detail>\r\n" +
" <detail> attribute 2 of detail b </detail>\r\n" +
"\r\n" +
" </detail-b>\r\n" +
"\r\n" +
"\r\n" +
"</Details>");
System.out.println(map);
// {Details={detail-a={detail=[ attribute 1 of detail a , attribute 2 of detail a , attribute 3 of detail a ]},
// detail-b={detail=[ attribute 1 of detail b , attribute 2 of detail b ]}}, #omit-xml-declaration=yes}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.