如何解析不同的节点名称xml

时间:2015-10-16 07:19:27

标签: java xml xml-parsing

服务给我一个xml结构。

<Veriler> 
    <ACSEL GUNLUKYUKSEK="61.00000" GUNLUKDUSUK="58.50000" TARIH="16.10.2015 10:02:59"/> 
    <ACSELBE GUNLUKYUKSEK="44.05000" GUNLUKDUSUK="42.00000" TARIH="16.10.2015 00:00:00"/> 
    <ACSELLE GUNLUKYUKSEK="55.00000" GUNLUKDUSUK="55.00000" TARIH="16.10.2015 00:00:00"/> 
    <ACSELR GUNLUKYUKSEK="18.00000" GUNLUKDUSUK="18.00000" TARIH="16.10.2015 00:00:00"/> 
    <ADANA GUNLUKYUKSEK="6.62000" GUNLUKDUSUK="6.62000" TARIH="16.10.2015 09:46:01"/> 
    <ADBGR GUNLUKYUKSEK="4.48000" GUNLUKDUSUK="4.48000" TARIH="16.10.2015 09:31:04"/> 
<Veriler>

我想像这样解析它。

        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder;
        Document doc = null;
        try {
            builder = factory.newDocumentBuilder();
            doc = builder.parse(new InputSource(new StringReader(str)));
        } catch (Exception e) {
            e.printStackTrace();
        }

        NodeList nList = doc.getElementsByTagName("???");

        for (int temp = 0; temp < nList.getLength(); temp++) {

            Node nNode = nList.item(temp);
            if (nNode.getNodeType() == Node.ELEMENT_NODE) {

                Element eElement = (Element) nNode;

                repo.setGUNLUKHACIM(eElement.getAttribute("GUNLUKYUKSEK"));

            }

但是所有节点必须与此代码具有相同的标记名。我该如何解决呢?

1 个答案:

答案 0 :(得分:0)

1)我认为您应该考虑将XML结构更改为:

<Veriler> 
    <Item name="ACSEL" GUNLUKYUKSEK="61.00000" GUNLUKDUSUK="58.50000" TARIH="16.10.2015 10:02:59"/> 
...
</Veriler> 

2)这样你就可以解析问题中的XML。只需找到“Veriler”的子节点并迭代......

Document doc = null;
         NodeList list = doc.getElementsByTagName("Veriler");
         Node node = list.item(0);
         Element element = (Element) node;
         NodeList nl = element.getChildNodes();
         for (int i = 0; i < nl.getLength(); i++){
             ((Element) nl.item(i)).getAttribute("GUNLUKYUKSEK");
         }