0

我正在尝试编写 DOM XML 解析。我的 XML 文件

<?xml version="1.0"?>
<BLAH>
    <AgentNm type="citi1">
        <accName>accName1</accName>
        <accType>accType1</accType>
        <someThing>someThing1</someThing>
        <amt>100000</amt>
    </AgentNm>
    <AgentNm type="citi2">
        <accName>accName2</accName>
        <accType>accType2</accType>
        <someThing>someThing2</someThing>
        <amt>200000</amt>
    </AgentNm>
</BLAH>

我尝试遵循java代码

DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
            DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
            Document doc = docBuilder.parse (new File("c:\\file.xml"));
            // normalize text representation
            doc.getDocumentElement ().normalize ();
            System.out.println ("Root element of the doc is " +doc.getDocumentElement().getNodeName());
            NodeList agentNm = doc.getElementsByTagName("AgentNm");
            int totalAgentNm = agentNm.getLength();
            System.out.println("Total no of Agents : " + totalAgentNm);
            for(int s=0; s<agentNm.getLength() ; s++){
                Node firstPersonNode = agentNm.item(s);
                if(firstPersonNode.getNodeType() == Node.ELEMENT_NODE){
                    Element firstPersonElement = (Element)firstPersonNode;
                    PrintNodeElem(firstPersonElement,"type");
                 }//end of if clause
            }//end of for loop with s var
        static void PrintNodeElem(Element nodeElem,String elem){
         NodeList someThingList = nodeElem.getElementsByTagName(elem);
         Element ageElement = (Element)someThingList.item(0);
         NodeList textAgeList = ageElement.getChildNodes();
         System.out.println(elem+" : " +((Node)textAgeList.item(0)).getNodeValue().trim());
    }

但是,当我尝试执行上述方法时,我得到空指针异常。谁能解释我,如何解决这个问题。

4

1 回答 1

1

如果您想要给定节点的属性,我建议您使用 XPath。这要容易得多。 http://onjava.com/onjava/2005/01/12/xpath.html

于 2012-04-05T20:03:09.450 回答