Page 1 of 1

How to read a SdtRun element- type mismatch

PostPosted: Tue Apr 12, 2011 8:25 am
by smer4
i m reading a .docx Dokument where a SdtRuns are inside or the P.

The problem is i gain a JAXBElement instead. And i can not convert it to the required type nevent if jax.getDeclaredType().equals(SdtRun.class) is TRUE.

Code: Select all
Body body = wmlDocumentEl.getBody();
      
      JAXBElement jax = null;      
      for (Object o: body.getEGBlockLevelElts()){//Body
         if (o instanceof P){         
            for (Object o1:((P) o).getParagraphContent()){//P               
               if(o1 instanceof R){
                  for(Object o3: ((R) o1).getRunContent()){                     
                     if(o3 instanceof Text){
                        System.out.println(((Text) o3).getValue());                              
                     }
                  }
               };
               if (o1 instanceof JAXBElement){
                  jax = (JAXBElement)o1;
               System.out.println(jax.getDeclaredType());                     
               if (jax.getDeclaredType().equals(SdtRun.class)){// this is true!!!
                  SdtRun std = (SdtRun) jax.getValue();// this is an error                                     
               CTSdtContentRun sb1 = ((SdtRun) o1).getSdtContent();                  
                  for(Object o2 :sb1.getContent()){//CTSdtContentRun                  
                     if(o2 instanceof R){//R                        
                        for(Object o3: ((R) o2).getRunContent()){                        
                           if(o3 instanceof Text){
                              System.out.println(((Text) o3).getValue());                              
                           }
                        }                  
                     }
                  }
               }//SdtRun
            }//   JAXBElement
         }//for p            
         }// if p   
      }//Body   


strange is if there is a R type i can simply cast it without any error!

Re: How to read a SdtRun element- type mismatch

PostPosted: Tue Apr 12, 2011 9:56 am
by jason
Actually your error is in the line

Code: Select all
CTSdtContentRun sb1 = ((SdtRun) o1).getSdtContent();     


where you are incorrectly trying to cast JAXBElement.

You probably meant:

Code: Select all
CTSdtContentRun sb1 = std.getSdtContent();


Alternatively (with svn or nightly) you could use the new interface getContent(), which gives you access to the contents without having to worry which type (block, run, row, cell) of sdt you are dealing with.