简体   繁体   中英

Passing Attributes from startElement to EndElement in SAX

We are trying to parse an XML using SAX Parser. Our Environment: Java Version: 1.7

<wrappercell borderWidth="0.9f" border="NO_BORDER" colSpan="1">
        <phrase font="BOLD_ARIAL">
          <token>1234</token>
        </phrase>
</wrappercell>

In our startElement we are doing the below

public void startElement(String uri, String localName, String qName, Attributes attributes){
  if("wrappercell".equals(qName)){
     elemenstack.push(attributes);
  }else if("phrase".equals(qName)){
     elemenstack.push(attributes);
  }
}

In our EndElement we wanted to refer to the attributes which we pushed during the startelement

public void endElement(String uri, String localName, String qName) throws SAXException {
  if("wrappercell".equals(qName)){
     System.out.println(((Attributes)elemenstack.pop()).getLength());
  }else if("phrase".equals(qName)){
     System.out.println(((Attributes)elemenstack.pop()).getLength());
  }

}

This always returns zero for getLength(). We refer the other Ques which says that attributes objects has the same instances at each startelement.

Is there an option other than the below which we tried such that we can refer the startelement values in endelement;

Our Plan for solution

public void startElement(String uri, String localName, String qName, Attributes attributes){
  if("wrappercell".equals(qName)){
     elementAttribute.put(attribute.getQName(1),attributes.getValue(1));
     elemenstack.push(elementAttribute);

  }else if("phrase".equals(qName)){
    elementAttribute.put(attribute.getQName(1),attributes.getValue(1));
     elemenstack.push(elementAttribute);

  }
}

public void endElement(String uri, String localName, String qName) throws SAXException {
  if("wrappercell".equals(qName)){
     System.out.println(((HashMap<String,String>)elemenstack.pop()).size());
  }else if("phrase".equals(qName)){
     System.out.println(((HashMap<String,String>)elemenstack.pop()).size());
  }

}

Not a direct answer to your question, but using StAX instead of SAX is much easier for issues like that.

SAX is a push-parser, meaning it pushes the events to you by executing your callback method.

StAX is a pull-parser, meaning that you request the next event from the stream. This allows you to use the call stack in your code to control "context".

Both are shipped with Java 7.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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