使用Sax解析访问xml中的节点

时间:2014-03-10 14:12:10

标签: java xml xml-parsing

我试图解析xml文件..并试图读取员工节点......

<?xml version="1.0" encoding="UTF-8"?>
<employees>
  <employee id="111">
    <firstName>Rakesh</firstName>
    <lastName>Mishra</lastName>
    <location>Bangalore</location>
    <secretary>
        <employee id="211">
            <firstName>Andy</firstName>
            <lastName>Mishra</lastName>
            <location>Bangalore</location>
        </employee>
    </secretary>
  </employee>
  <employee id="112">
    <firstName>John</firstName>
    <lastName>Davis</lastName>
    <location>Chennai</location>
  </employee>
  <employee id="113">
    <firstName>Rajesh</firstName>
    <lastName>Sharma</lastName>
    <location>Pune</location>
  </employee>
</employees>  

在我的经纪人中..我有以下......

    class SaxHandler extends DefaultHandler{


@Override
public void startElement(String uri, String localName, String qName,
        Attributes attributes) throws SAXException {

    if(qName.equals("employee")){           
        System.out.print("Its an employee ...and not an Secretary");
        /*for(int i=0;i< attributes.getLength();i++){
            System.out.print("Attr " +attributes.getQName(i)+ " Value " +attributes.getValue(i));
        }*/
        System.out.println();
    }


}

我如何知道该员工是否是秘书

此致

1 个答案:

答案 0 :(得分:1)

您需要在if内添加另一个startElement来检测secretary启动元素事件,并设置一个标记,当您在employee标记内时可以测试该标记。然后在离开secretary元素时重置标志。例如

class SaxHandler extends DefaultHandler {

     private boolean insideSecretaryTag = false;

     @Override
     public void startElement(...) throws SAXException {

         if(qName.equals("employee")){           
             if(insideSecretaryTag) {
                // this is a secretary
             } else {
                // not a secretary
             }
         }

         if(qName.equals("secretary")){           
             insideSecretaryTag = true;
         }

     public void endElement(...) {
        if(qName.equals("secretary")){           
            insideSecretaryTag = false;
        }
     }
}