如何获取给定节点的属性?

时间:2012-04-05 19:37:53

标签: java xml-parsing

我正在尝试编写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());
    }

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

1 个答案:

答案 0 :(得分:1)

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