0

`I am currently writing a program to convert Excel files into XML files, but I have encountered some errors from IDEA that prompt me: ***Exception in thread "main" java.lang.NoSuchMethodError: 'org.apache.xmlbeans.XmlOptions org.apache.xmlbeans.XmlOptions.setDisallowDocTypeDeclaration(boolean)'


I had tried many methods but no use

Here are my codes:

package com.ericsson.function.util;

import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.w3c.dom.*;

import javax.swing.*;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.*;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import java.io.*;

public class EasytestlinkUtil {

    private static String excelPath = "C:\\Users\\Administrator\\Desktop\\hahaha.xlsx";
    private static String sheetName = "test";
    private static String xmlPath = ".";

    public void processToXml(String excelPath, String sheetName, String xmlPath) {
        try {
            // Load the Excel file
            FileInputStream excelFile = new FileInputStream(new File(excelPath));
            Workbook workbook = new XSSFWorkbook(excelFile);
            Sheet sheet = workbook.getSheet(sheetName);

            // Create the root element for the XML
            DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
            DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
            Document doc = dBuilder.newDocument();
            Element rootElement = doc.createElement("testcases");
            doc.appendChild(rootElement);

            // Process each row in the Excel sheet starting from row 4
            for (int rowNum = 4; rowNum <= sheet.getLastRowNum(); rowNum++) {
                Row row = sheet.getRow(rowNum);
                String tcId = row.getCell(1).getStringCellValue();
                String tcSummary = row.getCell(2).getStringCellValue();
                String tcPrecondition = row.getCell(3).getStringCellValue();
                String tcPriority = row.getCell(9).getStringCellValue();
                String tcAutomationAbleStr = row.getCell(10).getStringCellValue();
                String tcAction = row.getCell(4).getStringCellValue();
                String tcException = row.getCell(5).getStringCellValue();

                // Create the testcase element
                Element testcase = doc.createElement("testcase");
                rootElement.appendChild(testcase);

                // Create and append elements for testcase details
                createAndAppendElement(doc, testcase, "internalid", tcId.replace("TC", "").replace(".", ""));
                createAndAppendElement(doc, testcase, "name", tcSummary.substring(0, Math.min(100, tcSummary.length())));
                createAndAppendElement(doc, testcase, "summary", tcSummary);
                createAndAppendElement(doc, testcase, "preconditions", tcPrecondition.replace('\n', '\u2028'));

                // Create steps element
                Element steps = doc.createElement("steps");
                testcase.appendChild(steps);

                // Create step element
                Element step = doc.createElement("step");
                steps.appendChild(step);

                createAndAppendElement(doc, step, "step_number", "1");
                createAndAppendElement(doc, step, "actions", tcAction);
                createAndAppendElement(doc, step, "expectedresults", tcException);
                createAndAppendElement(doc, step, "importance", getImportanceValue(tcPriority));
                createAndAppendElement(doc, step, "execution_type", "Yes".equals(tcAutomationAbleStr) ? "2" : "1");
            }

            // Create a pretty-formatted XML string
            TransformerFactory transformerFactory = TransformerFactory.newInstance();
            Transformer transformer = transformerFactory.newTransformer();
            transformer.setOutputProperty(OutputKeys.INDENT, "yes");
            transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");
            DOMSource source = new DOMSource(doc);
            StreamResult result = new StreamResult(new File(xmlPath));
            transformer.transform(source, result);

            System.out.println("The XML file is successfully created");
        } catch (Exception e) {
            e.printStackTrace();
            JOptionPane.showMessageDialog(null, "Error: " + e.getMessage());
        }
    }

    private void createAndAppendElement(Document doc, Element parentElement, String elementName, String elementValue) {
        Element element = doc.createElement(elementName);
        element.appendChild(doc.createTextNode(elementValue));
        parentElement.appendChild(element);
    }

    private String getImportanceValue(String priority) {
        if ("High".equals(priority)) {
            return "3";
        } else if ("Medium".equals(priority)) {
            return "2";
        } else {
            return "1";
        }
    }

    public static void main(String[] args) {
        EasytestlinkUtil converter = new EasytestlinkUtil();
        converter.processToXml(excelPath, sheetName, xmlPath);
    }
}

Here are my Modules and Libraries:

poi 4.0.1 xml beans 5.1.1 In my previous attempts, an error occurred that DocumntFactory not found in xmlbeans, I suspect there is a conflict between my dependencies.So I streamlined the dependencies of my project structure in IDEA, but the following issues arose: 'org.apache.xmlbeans.XmlOptions org.apache.xmlbeans.XmlOptions.setDisallowDocTypeDeclaration(boolean)'

I hope anyone can help me to find this method : setDisallowDocTypeDeclaration

In fact,I have already written this code in Python and it can run normally, I am a green hand in java, and I think apache POI and xmlbeans are so unfriendly to me...

And here are my python source code, I hope it can help you to help me locate problem:

from tkinter import messagebox, filedialog, Button, Entry, Label, Tk

import openpyxl
from xml.etree.ElementTree import Element, SubElement, tostring
from xml.dom import minidom


def process_excel_to_xml(excel_file_path, sheet_name, output_xml_path):
    try:
        # Load the Excel file
        workbook = openpyxl.load_workbook(excel_file_path)
        sheet = workbook[sheet_name]
    except FileNotFoundError:
        messagebox.showerror("Error", "File not found. Please choose a valid Excel file.")
        return
    except KeyError:
        messagebox.showerror("Error", f"Sheet '{sheet_name}' not found in the Excel file.")
        return

    # Load the Excel file
    workbook = openpyxl.load_workbook(excel_file_path)
    sheet = workbook[sheet_name]

    # Create the root element for the XML
    root = Element("testcases")

    # Process each row in the Excel sheet starting from row 4
    for row in sheet.iter_rows(min_row=4, values_only=True):
        # Extract the values from the Excel columns
        tc_id = row[1]
        tc_summary = row[2]
        tc_preconditions = row[3]
        tc_priority = row[9]
        tc_automationable = row[10]
        tc_action = row[4]
        tc_exception = row[5]

        # Skip the row if TC ID is empty
        if not tc_id:
            continue

        # Create the testcase element
        testcase = SubElement(root, "testcase")
        testcase.set("internalid", tc_id.replace("TC", "").replace(".", ""))
        testcase.set("name", tc_summary.strip()[:100] if tc_summary else "")

        # Create the summary element
        summary = SubElement(testcase, "summary")
        summary.text = "<p>{}</p>".format(tc_summary[:100]) if tc_summary else ""

        # Create the preconditions element
        preconditions = SubElement(testcase, "preconditions")
        preconditions.text = "<p>{}</p>".format(tc_preconditions.replace('\n', '<br/>')) if tc_preconditions else ""

        steps = SubElement(testcase, "steps")

        # Combine TC Action (E column) and TC Exception (F column) into one string with line breaks
        combined_actions = "\n".join("<p>{}</p>".format(action.strip()) for action in str(tc_action).split('\n') if action.strip())
        combined_exceptions = "\n".join("<p>{}</p>".format(exception.strip()) for exception in str(tc_exception).split('\n') if exception.strip())

        # Create the step element
        step = SubElement(steps, "step")
        step_number = SubElement(step, "step_number")
        step_number.text = "<![CDATA[1]]>"

        # Create the actions element
        actions = SubElement(step, "actions")
        actions.text = combined_actions

        # Create the expectedresults element
        expectedresults = SubElement(step, "expectedresults")
        expectedresults.text = combined_exceptions

        # Create the importance element
        importance = SubElement(testcase, "importance")
        if tc_priority == "High":
            importance.text = "<![CDATA[3]]>"
        elif tc_priority == "Medium":
            importance.text = "<![CDATA[2]]>"
        else:
            importance.text = "<![CDATA[1]]>"

        # Create the execution_type element
        execution_type = SubElement(testcase, "execution_type")
        if tc_automationable == "Yes":
            execution_type.text = "<![CDATA[2]]>"
        elif tc_automationable == "No":
            execution_type.text = "<![CDATA[1]]>"

    # Create a pretty-formatted XML string
    xml_string = minidom.parseString(tostring(root)).toprettyxml(indent="    ", newl="\n", encoding="utf-8").decode()

    # Remove empty lines caused by pretty-printing
    xml_lines = xml_string.split("\n")
    xml_lines = [line for line in xml_lines if line.strip()]
    xml_string = "\n".join(xml_lines)

    # Write the XML string to a file with UTF-8 encoding
    with open(output_xml_path, "w", encoding="utf-8") as xml_file:
        xml_file.write(xml_string)

    messagebox.showinfo("Info", "The XML file is successfully created")


def choose_file():
    file_path = filedialog.askopenfilename(filetypes=[("Excel files", "*.xlsx")])
    if file_path:
        entry_file_path.delete(0, "end")
        entry_file_path.insert(0, file_path)


def choose_output_folder():
    output_folder = filedialog.askdirectory()
    if output_folder:
        entry_output_folder.delete(0, "end")
        entry_output_folder.insert(0, output_folder)


def generate_xml():
    excel_file_path = entry_file_path.get()
    sheet_name = entry_sheet_name.get()
    output_folder = entry_output_folder.get()

    if not excel_file_path or not sheet_name or not output_folder:
        messagebox.showwarning("Warning", "Please enter the file path, sheet name, and choose the output folder.")
        return

    output_xml_path = f"{output_folder}/output.xml"
    process_excel_to_xml(excel_file_path, sheet_name, output_xml_path)


# Create the main application window
root = Tk()
root.title("Easy Testlink XML generator")

# Create widgets
label_file_path = Label(root, text="Excel File:")
entry_file_path = Entry(root, width=40)
button_browse = Button(root, text="Browse", command=choose_file)

label_sheet_name = Label(root, text="Sheet Name:")
entry_sheet_name = Entry(root, width=40)

label_output_folder = Label(root, text="Output Folder:")
entry_output_folder = Entry(root, width=40)
button_browse_output = Button(root, text="Browse", command=choose_output_folder)

button_generate = Button(root, text="Generate XML", command=generate_xml)

# Grid layout
label_file_path.grid(row=0, column=0, padx=5, pady=5)
entry_file_path.grid(row=0, column=1, padx=5, pady=5)
button_browse.grid(row=0, column=2, padx=5, pady=5)

label_sheet_name.grid(row=1, column=0, padx=5, pady=5)
entry_sheet_name.grid(row=1, column=1, padx=5, pady=5)

label_output_folder.gr`your text`id(row=2, column=0, padx=5, pady=5)
entry_output_folder.grid(row=2, column=1, padx=5, pady=5)
button_browse_output.grid(row=2, column=2, padx=5, pady=5)

button_generate.grid(row=3, columnspan=3, padx=5, pady=10)

# Create a prompt area
prompt_label = Label(root, text="Please use a standard TA template Excel file!!!", fg="red")
prompt_label.config(font=("Arial", 14, "italic"))
prompt_label.grid(row=4, columnspan=3, padx=5, pady=10)
# Pack the label to display it on the window


root.mainloop()

`

New contributor
peter griffin is a new contributor to this site. Take care in asking for clarification, commenting, and answering. Check out our Code of Conduct.
1
  • This error generally means that you have the wrong version of a dependency on your classpath. 2 mins ago

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Browse other questions tagged or ask your own question.