Get root style name

Hello,

We are using the Aspose Words for Java library to transform the input word documents into a custom model.

The data from the input docx file is selected based on the paragraph style. Paragraphs having ‘Heading 1’ style are mapped to something while paragraphs having ‘Heading 2’ style have another mapping.

Is there a possibility to detect the root style when having Word documents with custom headings?

In my case, the document contains the following hierarchy:

‘Heading 1 child’ style is based on ‘Heading 1 Unnumbered’ style while ‘Heading 1 Unnumbered’ is based on ‘Heading 1’.

I need to retrieve the root style name or it’s identifier - ‘Heading 1’ for both ‘Heading 1 child’ and ‘Heading 1 Unnumbered’ custom styles.

private String getBaseStyleName(Paragraph paragraph) {
    paragraph.getParagraphFormat().getStyle().getName(); // current style name
    paragraph.getParagraphFormat().getStyle().getBaseStyleName(); // returns only direct parent style name
    paragraph.getParagraphFormat().getStyleIdentifier(); // current style identifier
    return ??;
}

I’ve attached a test document.

custom-headings.zip (10.3 KB)

@mihail.manoli,

Please check if the following code of Aspose.Words for Java is acceptable for you to get parent (root) Styles of Paragraphs in Word document?

Document doc = new Document("C:\\temp\\custom-headings\\custom-headings.docx");

for (Paragraph para : (Iterable<Paragraph>) doc.getChildNodes(NodeType.PARAGRAPH, true))
    System.out.println(para.getParagraphFormat().getStyleName() + " --> " + getBaseStyleName(para));

public static String getBaseStyleName(Paragraph paragraph) {

    Style style = paragraph.getParagraphFormat().getStyle();
    while (style.getStyleIdentifier() == StyleIdentifier.USER)
        style = paragraph.getDocument().getStyles().get(style.getBaseStyleName());

    return style.getName();
}
1 Like

This is perfect!

Thank you,
Mihail