Untitled
unknown
plain_text
2 years ago
3.6 kB
6
Indexable
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 test {
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("//ivz-eintrag[redner]/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"));
// Add the Redner object to the list
rednerList.add(redner);
}
// Output the Redner objects
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
public Redner() {
}
public Redner(String vorname, String nachname, String fraktion) {
this.vorname = vorname;
this.nachname = nachname;
this.fraktion = fraktion;
}
public String getVorname() {
return vorname;
}
public void setVorname(String vorname) {
this.vorname = vorname;
}
public String getNachname() {
return nachname;
}
public void setNachname(String nachname) {
this.nachname = nachname;
}
public String getFraktion() {
return fraktion;
}
public void setFraktion(String fraktion) {
this.fraktion = fraktion;
}
@Override
public String toString() {
return "Redner{vorname='" + vorname + "', nachname='" + nachname + "', fraktion='" + fraktion + "'}";
}
}
Editor is loading...
Leave a Comment