Search code examples
javadocxdocx4j

Get the title or alias of a content control in docx4j


I would like to know if it is possible to get the title of a content control. It is very easy to get the Tag but the title called alias in the XML is unreachable.

When I ask the class I get the mean "javax.xml.bind.JAXBElement"

Here is what I want in the xml

<w:sdt>
<w:sdtPr>
<w:rPr>
<w:rStyle w:val="Calibri8"/>
</w:rPr>
<w:alias w:val="The title"/>            <== I want this little guy
<w:tag w:val="RULE["BaseSalary"]"/>
<w:id w:val="51973609"/>
<w:placeholder>
<w:docPart w:val="DefaultPlaceholder_1081868574"/>
</w:placeholder> 

Here is how I get my Tag :

for (Object alias : al) {   

                    if ( alias.getClass().toString().contains("org.docx4j.wml.Tag")) {

                        //gets the Tag
                        String CTagVal = ((org.docx4j.wml.Tag) alias).getVal();

                        // If the tag contain ....
                        if (CTagVal.contains("RULE") || CTagVal.contains("CAL") )  {  
        ...........................

It's really easy to get the Tag because there is a class called Tag but why doesn't "alias" class exists ? But more importantly is there a way to get it ? Or ??? Thx in advance


Solution

  • Well you could also do this :

    // This is for the alias
    @SuppressWarnings({ "unchecked", "rawtypes" })
         Alias getAlias(SdtPr element) {
    
            for (Object o : element.getRPrOrAliasOrLock()) {
                if (o instanceof JAXBElement  && ((JAXBElement)o).getValue() instanceof Alias) {
                    return ((JAXBElement<Alias>)o).getValue();
                }
            }
            return null;
        }
    
        // this is for the tag
         Tag getTag(SdtPr element) {
    
            for (Object o : element.getRPrOrAliasOrLock()) {
                if (o instanceof Tag) {
                    return (Tag) o;
                }
            }
            return null;
        }
    

    Of course you need to send your sdtPr Element : You could do something like this :

    for(SdtElement sdtElement: listOfSdtElements){  // if you have multiple sdtelements
                    SdtPr pr = sdtElement.getSdtPr();
    
                    //Gets tags and alias
                    Tag tag = getTag( pr);
                    String tagVal = "";
                    Alias alias = getAlias( pr);
    
                    // if it is indeed an alias
                    if(alias!=null){  // needed or else nullexception
    
                        String aliasVal = alias.getVal();
    
                        if(tag != null){  // needed or else nullexception
                            //gets the Tag
                            tagVal = tag.getVal();
    
                        }
                 .... ....... ...... ..... 
                     }
       }