简体   繁体   English

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

[英]Access a node in a xml using Sax parsing

Am trying to parse a xml file ..and trying to read the employee nodes... 我正在尝试解析一个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>  

And in my handler ..I have the below... 在我的处理程序中..我有以下内容...

    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();
    }


}

How can i know if the the employee is a secretary or not 我怎么知道员工是否是秘书

Regards 问候

You need to add another if inside startElement to detect the secretary start element event, and set a flag that you can test when you are inside the employee tag. 您需要在startElement内部添加另一个if以检测secretary开始元素事件,并设置一个标记,以便当您在employee标记内部时可以进行测试。 Then you reset the flag when you leave the secretary element. 然后,在离开secretary元素时重置标志。 For example 例如

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;
        }
     }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM