Added XML parsing

master
Moritz 2026-11-15 15:36:27 +01:00
parent 7fc42e171d
commit c572eee5c5
2 changed files with 142 additions and 2 deletions

View File

@ -52,7 +52,7 @@ public class config_editor {
config_data = jsonc_parse.parse_file(config_file_path);
break;
case XML:
// Call methods to parse XML file
config_data = xml_parse.parse_file(config_file_path);
break;
default:
System.err.println("No valid config file type detected.");

View File

@ -1,3 +1,143 @@
import java.io.IOException;
import java.io.InputStream;
import java.io.StringReader;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import javax.xml.XMLConstants;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
public class xml_parse {
public static Map<String, Object> parse(String xml) {
if (xml == null) {
throw new IllegalArgumentException("XML content must not be null.");
}
try {
return parseDocument(new InputSource(new StringReader(xml)));
} catch (ParserConfigurationException exception) {
throw new IllegalStateException("Could not configure the XML parser.", exception);
} catch (SAXException | IOException exception) {
throw new IllegalArgumentException("Invalid XML content.", exception);
}
}
public static Map<String, Object> parse_file(String filePath) throws IOException {
try (InputStream input = Files.newInputStream(Paths.get(filePath))) {
try {
return parseDocument(new InputSource(input));
} catch (ParserConfigurationException exception) {
throw new IllegalStateException("Could not configure the XML parser.", exception);
} catch (SAXException exception) {
throw new IllegalArgumentException("Invalid XML in file: " + filePath, exception);
}
}
}
private static Map<String, Object> parseDocument(InputSource source)
throws ParserConfigurationException, SAXException, IOException {
Document document = createDocumentBuilder().parse(source);
Element root = document.getDocumentElement();
if (root == null) {
throw new IllegalArgumentException("XML document has no root element.");
}
Map<String, Object> result = new LinkedHashMap<String, Object>();
addAttributes(root, result);
StringBuilder text = new StringBuilder();
for (Node child = root.getFirstChild(); child != null; child = child.getNextSibling()) {
if (child.getNodeType() == Node.ELEMENT_NODE) {
Element element = (Element) child;
addChildValue(result, element.getTagName(), parseElement(element));
} else if (child.getNodeType() == Node.TEXT_NODE
|| child.getNodeType() == Node.CDATA_SECTION_NODE) {
text.append(child.getNodeValue());
}
}
String rootText = text.toString().trim();
if (!rootText.isEmpty()) {
result.put("#text", rootText);
}
return result;
}
private static Object parseElement(Element element) {
Map<String, Object> values = new LinkedHashMap<String, Object>();
addAttributes(element, values);
StringBuilder text = new StringBuilder();
boolean hasChildElements = false;
for (Node child = element.getFirstChild(); child != null; child = child.getNextSibling()) {
if (child.getNodeType() == Node.ELEMENT_NODE) {
hasChildElements = true;
Element childElement = (Element) child;
addChildValue(values, childElement.getTagName(), parseElement(childElement));
} else if (child.getNodeType() == Node.TEXT_NODE
|| child.getNodeType() == Node.CDATA_SECTION_NODE) {
text.append(child.getNodeValue());
}
}
String elementText = text.toString().trim();
if (hasChildElements || !values.isEmpty()) {
if (!elementText.isEmpty()) {
values.put("#text", elementText);
}
return values;
}
return elementText;
}
private static void addAttributes(Element element, Map<String, Object> values) {
NamedNodeMap attributes = element.getAttributes();
for (int i = 0; i < attributes.getLength(); i++) {
Node attribute = attributes.item(i);
values.put("@" + attribute.getNodeName(), attribute.getNodeValue());
}
}
private static void addChildValue(Map<String, Object> values, String name, Object value) {
if (!values.containsKey(name)) {
values.put(name, value);
return;
}
Object existing = values.get(name);
List<Object> repeatedValues;
if (existing instanceof List<?>) {
repeatedValues = new ArrayList<Object>((List<?>) existing);
} else {
repeatedValues = new ArrayList<Object>();
repeatedValues.add(existing);
}
repeatedValues.add(value);
values.put(name, repeatedValues);
}
private static DocumentBuilder createDocumentBuilder() throws ParserConfigurationException {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
factory.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);
factory.setFeature("http://xml.org/sax/features/external-general-entities", false);
factory.setFeature("http://xml.org/sax/features/external-parameter-entities", false);
factory.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
factory.setAttribute(XMLConstants.ACCESS_EXTERNAL_DTD, "");
factory.setAttribute(XMLConstants.ACCESS_EXTERNAL_SCHEMA, "");
factory.setXIncludeAware(false);
factory.setExpandEntityReferences(false);
return factory.newDocumentBuilder();
}
}