Java jdom2 read parse xml examples

https‮gi.www//:‬iftidea.com

JDOM2 is a Java library for reading, manipulating, and writing XML documents. Here are some examples of how to use JDOM2 to read and parse XML:

  1. Parsing an XML document from a file:
File inputFile = new File("input.xml");
SAXBuilder saxBuilder = new SAXBuilder();
Document document = saxBuilder.build(inputFile);
  1. Parsing an XML document from a string:
String xmlString = "<root><element>value</element></root>";
SAXBuilder saxBuilder = new SAXBuilder();
Document document = saxBuilder.build(new StringReader(xmlString));
  1. Getting the root element of an XML document:
Element rootElement = document.getRootElement();
  1. Getting the value of an element:
String elementValue = rootElement.getChildText("element");
  1. Getting the value of an attribute:
String attributeValue = rootElement.getAttributeValue("attribute");
  1. Navigating the XML tree using XPath:
XPathFactory xpfac = XPathFactory.instance();
XPathExpression<Element> xp = xpfac.compile("//element", Filters.element());
List<Element> elementList = xp.evaluate(document);

These examples should give you a good idea of how to use JDOM2 to read and parse XML documents in Java.