Untitled

mail@pastecode.io avatar
unknown
plain_text
7 months ago
2.9 kB
4
Indexable
Never
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathFactory;

import org.w3c.dom.Document;
import org.w3c.dom.NodeList;

import java.util.ArrayList;
import java.util.List;

public class XmlParser {

    public static void main(String[] args) {
        String xmlFilePath = "/home/melih/IdeaProjects/Uebung2/src/main/resources/1.xml";

        try {
            // XML Parsing using DocumentBuilderFactory
            DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
            docBuilderFactory.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
            Document document = docBuilderFactory.newDocumentBuilder().parse(xmlFilePath);

            // Create an XPath expression to select all 'redner' elements
            XPathFactory xPathFactory = XPathFactory.newInstance();
            XPath xpath = xPathFactory.newXPath();
            XPathExpression expression = xpath.compile("//redner");

            // Evaluate the XPath expression against the document
            NodeList nodeList = (NodeList) expression.evaluate(document, XPathConstants.NODESET);

            // Create a list to store Redner objects
            List<Redner> rednerList = new ArrayList<>();

            // Iterate through 'redner' elements and create Redner objects
            for (int i = 0; i < nodeList.getLength(); i++) {
                Redner redner = new Redner();
                redner.setVorname(evaluateXPath(xpath, nodeList.item(i), "vorname"));
                redner.setNachname(evaluateXPath(xpath, nodeList.item(i), "nachname"));
                redner.setFraktion(evaluateXPath(xpath, nodeList.item(i), "fraktion"));

                // Füge das Redner-Objekt zur Liste hinzu
                rednerList.add(redner);
            }

            // Ausgabe der Redner-Objekte
            System.out.println("Redner-Objekte:");
            for (Redner redner : rednerList) {
                System.out.println(redner);
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static String evaluateXPath(XPath xpath, Object item, String expression) throws Exception {
        XPathExpression xpathExpression = xpath.compile(expression);
        return (String) xpathExpression.evaluate(item, XPathConstants.STRING);
    }
}

class Redner {
    private String vorname;
    private String nachname;
    private String fraktion;

    // Konstruktoren, Getter und Setter

    @Override
    public String toString() {
        return "Redner{vorname='" + vorname + "', nachname='" + nachname + "', fraktion='" + fraktion + "'}";
    }
}
Leave a Comment