使用DOM Parser解析xml的难度

时间:2014-10-08 06:23:06

标签: java xml parsing

如何获取嵌套在下面的分组标记下的名称标记的值。我能够获得嵌套在列标签下的名称的值。 如何在分组标记下获取名称的嵌套值。分组标记下的名称标记的属性不同。

<Services>
    <Service name="check" regrx="" reverseExtention="" > 
    <File rootProfile="Test" extension="txt" seperator="," targetSeperator="q12"> 
    <Columns> 
    <name id="1" usn="2234" dob="030395" age="55" validity="20" />
    <name id="2" usn="I_TWO" dob="true" age="10" validity="44" >
           <grouped>
                <name id="343" value1="TYPE0" value2="TYPE4" type=""  value7="1"></name>
                <name id="564" value1="TYPE6" value2="TYPE7" type=""  value7="0"></name>
           </grouped>
    </name>  
    <name id="3" usn="55453" dob="050584" age="35" validity="123"/>
    <name id="5" usn="7565" dob="050488" age="44" validity="55"/>
    </Columns>
    </File>
    </Service>
</Services>

以下是我的代码

 import java.io.File;
    import javax.xml.parsers.DocumentBuilder;
    import javax.xml.parsers.DocumentBuilderFactory;
    import org.w3c.dom.Document;
    import org.w3c.dom.Element;
    import org.w3c.dom.Node;
    import org.w3c.dom.NodeList;

    public class Test {
        public static void main(String[] args) {
            // TODO Auto-generated method stub
            try{
            File fXmlFile = new File("D://test3.xml");
            DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
            DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
            Document doc = dBuilder.parse(fXmlFile);
            doc.getDocumentElement().normalize();
            NodeList nodeList0 = doc.getElementsByTagName("Service");
            NodeList nodeList1 = doc.getElementsByTagName("File");
            NodeList nodeList2 = doc.getElementsByTagName("name");
            NodeList nodeList3=  doc.getElementsByTagName("grouped");
            System.out.println("Root element :" + doc.getDocumentElement().getNodeName());
            for (int temp0 = 0; temp0 < nodeList0.getLength(); temp0++) {
                Node node0 = nodeList0.item(temp0);
                System.out.println("\nElement type :" + node0.getNodeName());
                Element Service = (Element) node0;
                System.out.println("----" + temp0 + "-------");
                if (node0.getNodeType() == Node.ELEMENT_NODE) {
                    System.out.println("Name : " + Service.getAttribute("name"));
                    System.out.println("regrx : " + Service.getAttribute("regrx"));
                System.out.println("reverex"+Service.getAttribute("reverseExtention"));
                    for (int temp = 0; temp < nodeList1.getLength(); temp++) {
                        Node node1 = nodeList1.item(temp);
                        System.out.println("------file" + temp + "--------");
                        System.out.println("\nElement type :" + node1.getNodeName());
                        Element File = (Element) node1;

                        //used for getting file level
                        if (node1.getNodeType() == Node.ELEMENT_NODE) {
                            System.out.println("rootProfile:" + File.getAttribute("rootProfile"));
                            System.out.println("extension  : " + File.getAttribute("extension"));
                            System.out.println("seperator  : " + File.getAttribute("seperator"));
                            System.out.println("targetSeperator  : " +        File.getAttribute("targetSeperator"));

                          for(int temp2=0;temp2<nodeList2.getLength();temp2++){
                                Node node2 = nodeList2.item(temp2);
                                Element name = (Element) node2;

                                if (node2.getNodeType() == Node.ELEMENT_NODE) {
                                    System.out.println("id:" + name.getAttribute("id"));
                                    System.out.println("usn  : " + name.getAttribute("usn"));
                                    System.out.println("dob  : " + name.getAttribute("dob"));
                                    System.out.println("age  : " + name.getAttribute("age"));
                                    System.out.println("validity  : " + name.getAttribute("validity"));

                                    //to get grouped node, the problem seems to be here                         
                                    Node node3=nodeList3.item(temp2);       
                                    if(node3.hasChildNodes()){      
                                    Element grouped=(Element)node3;
                                    if(node3.getNodeType()==Node.ELEMENT_NODE){
                                        System.out.println("id:" + grouped.getAttribute("id"));
                                        System.out.println("value1:" + grouped.getAttribute("value1"));
                                        System.out.println("value2:" + grouped.getAttribute("value2"));
                                        System.out.println("type:" + grouped.getAttribute("type"));
                                        System.out.println("value7:" + grouped.getAttribute("value7"));                                             
                                       }
                                    }

                                  } 
                                }           
                        }

                    }
                }   
            }
            }
            catch(Exception e){
                e.printStackTrace();
            }
        }
    }

2 个答案:

答案 0 :(得分:0)

如果您需要name下的嵌套 grouped标记,请询问grouped标记中的元素,而不是文档中的元素。

Document.getElementsByTagName()会根据该名称返回所有代码,在getElementsByTagName()上调用Element会返回{{1}的所有后代元素(例如孩子,孙子等)。

您可以安全地将Elemenent grouped投射到Node并在其上调用Element

getElementsByTagName()

输出是:

NodeList groupedNodeList = doc.getElementsByTagName("grouped");
for (int i = 0; i < groupedNodeList .getLength(); i++) {
    Element groupedElement = (Element) groupedNodeList .item(i);
    NodeList nameList = groupedElement.getElementsByTagName("name");

    // Here you go, you have the list of name tags UNDER grouped
    // Printing the id and value attributes of the name tag:
    for (int j = 0; j < nameList.getLength(); j++) {
        Element name = (Element) nameList.item(j);
        System.out.println("Found <name>: id=" + name.getAttribute("id"));
        System.out.println("\tvalue1=" + name.getAttribute("value1"));
        System.out.println("\tvalue2=" + name.getAttribute("value2"));
        System.out.println("\tvalue7=" + name.getAttribute("value7"));
    }
}

答案 1 :(得分:0)

以下是您修改后的代码

import java.io.File;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

public class Test {
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        try {
            File fXmlFile = new File("D://test3.xml");
            DocumentBuilderFactory dbFactory = DocumentBuilderFactory
                    .newInstance();
            DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
            Document doc = dBuilder.parse(fXmlFile);
            doc.getDocumentElement().normalize();
            NodeList nodeList0 = doc.getElementsByTagName("Service");
            NodeList nodeList1 = doc.getElementsByTagName("File");
            NodeList nodeList2 = doc.getElementsByTagName("name");
            NodeList nodeList3 = doc.getElementsByTagName("grouped");
            System.out.println("Root element :"
                    + doc.getDocumentElement().getNodeName());
            for (int temp0 = 0; temp0 < nodeList0.getLength(); temp0++) {
                Node node0 = nodeList0.item(temp0);
                System.out.println("\nElement type :" + node0.getNodeName());
                Element Service = (Element) node0;
                System.out.println("----" + temp0 + "-------");
                if (node0.getNodeType() == Node.ELEMENT_NODE) {
                    System.out
                    .println("Name : " + Service.getAttribute("name"));
                    System.out.println("regrx : "
                            + Service.getAttribute("regrx"));
                    System.out.println("reverex"
                            + Service.getAttribute("reverseExtention"));
                    for (int temp = 0; temp < nodeList1.getLength(); temp++) {
                        Node node1 = nodeList1.item(temp);
                        System.out.println("------file" + temp + "--------");
                        System.out.println("\nElement type :"
                                + node1.getNodeName());
                        Element File = (Element) node1;

                        // used for getting file level
                        if (node1.getNodeType() == Node.ELEMENT_NODE) {
                            System.out.println("rootProfile:"
                                    + File.getAttribute("rootProfile"));
                            System.out.println("extension  : "
                                    + File.getAttribute("extension"));
                            System.out.println("seperator  : "
                                    + File.getAttribute("seperator"));
                            System.out.println("targetSeperator  : "
                                    + File.getAttribute("targetSeperator"));

                            for (int temp2 = 0; temp2 < nodeList2.getLength(); temp2++) {
                                Node node2 = nodeList2.item(temp2);
                                Element name = (Element) node2;

                                if (node2.getNodeType() == Node.ELEMENT_NODE) {
                                    System.out.println("id:"
                                            + name.getAttribute("id"));
                                    System.out.println("usn  : "
                                            + name.getAttribute("usn"));
                                    System.out.println("dob  : "
                                            + name.getAttribute("dob"));
                                    System.out.println("age  : "
                                            + name.getAttribute("age"));
                                    System.out.println("validity  : "
                                            + name.getAttribute("validity"));

                                    // to get grouped node, the problem seems to
                                    // be here
                                    // Node node3 = nodeList3.item(temp2);
                                    NodeList grouped = node2.getChildNodes();
                                    if (grouped != null
                                            && grouped.getLength() > 0) {
                                        for (int ii = 0; ii < grouped
                                                .getLength(); ii++) {
                                            Node group = grouped.item(ii);
                                            {
                                                NodeList gropedNames = group
                                                        .getChildNodes();
                                                if (gropedNames != null
                                                        && gropedNames
                                                        .getLength() > 0) {
                                                    for (int jj = 0; jj < gropedNames
                                                            .getLength(); jj++) {
                                                        if (gropedNames
                                                                .item(jj) != null
                                                                && gropedNames
                                                                .item(jj)
                                                                .getAttributes() != null) {
                                                            System.out
                                                            .println(gropedNames
                                                                    .item(jj)
                                                                    .getAttributes()
                                                                    .getNamedItem(
                                                                            "id"));
                                                            System.out
                                                            .println(gropedNames
                                                                    .item(jj)
                                                                    .getAttributes()
                                                                    .getNamedItem(
                                                                            "value1"));
                                                            System.out
                                                            .println(gropedNames
                                                                    .item(jj)
                                                                    .getAttributes()
                                                                    .getNamedItem(
                                                                            "value2"));
                                                            System.out
                                                            .println(gropedNames
                                                                    .item(jj)
                                                                    .getAttributes()
                                                                    .getNamedItem(
                                                                            "value7"));
                                                        }
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }

                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}