我有一个这样的XML,必须解析它,并且需要在UI上以表格格式打印元素,或者如果我将获得JSON,那么我也可以做些事情。
但是我无法获取XML的所有元素,因为<type>
标签已经使用了多次。
<catalog>
<product productsname="Choclates">
<Parameters total="2">
<Subtype name="dairy milk">
<type>oreo</type>
<type>Silk</type>
<type>nuts</type>
</Subtype>
<Subtype name="Other">
<type>perk</type>
<type>kitkat</type>
<type>5 start</type>
</Subtype>
</Parameters>
</product>
<product productsname="Biscuits">
<Parameters total="3">
<Subtype name="parle">
<type>parle G</type>
<type>krack jack</type>
<type>monaco</type>
</Subtype>
<Subtype name="britannia">
<type>good day</type>
<type>50 50</type>
<type>bourbon</type>
<type>tiger</type>
</Subtype>
<Subtype name="Priya Gold">
<type>Italiano Cookies</type>
<type>Glucose V</type>
<type>Butter Bite</type>
<type>CNC</type>
<type>Marie Lite</type>
<type>Classic Cream</type>
</Subtype>
</Parameters>
</product>
我尝试了DOC分析器。
答案 0 :(得分:1)
这是一个使用jdom2库的示例:
public class Main {
public static void main(String[] args) {
org.jdom2.Document jdomDoc;
try {
jdomDoc = useDOMParser(new File("your_xml_file"));
List<Element> products = jdomDoc.getRootElement().getChildren("product");
for (Element product : products) {
System.out.println("----" + product.getAttributeValue("productsname"));
List<Element> subtypes = product.getChild("Parameters").getChildren("Subtype");
for (Element subtype : subtypes) {
System.out.println("--" + subtype.getAttributeValue("name"));
List<Element> types = subtype.getChildren("type");
for (Element type : types) {
System.out.println(type.getText());
}
}
}
} catch (Exception e) {e.printStackTrace();}
}
private static org.jdom2.Document useDOMParser(File fileName)
throws ParserConfigurationException, SAXException, IOException {
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
dbFactory.setIgnoringComments(true);
DocumentBuilder dBuilder;
dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(fileName);
DOMBuilder domBuilder = new DOMBuilder();
return domBuilder.build(doc);
}
}
上面产生了以下输出:
----Choclates --dairy milk oreo Silk nuts --Other perk kitkat 5 start ----Biscuits --parle parle G krack jack monaco --britannia good day 50 50 bourbon tiger --Priya Gold Italiano Cookies Glucose V Butter Bite CNC Marie Lite Classic Cream