Java jdom2 read parse xml examples
httpsgi.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:
- Parsing an XML document from a file:
File inputFile = new File("input.xml"); SAXBuilder saxBuilder = new SAXBuilder(); Document document = saxBuilder.build(inputFile);
- 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));
- Getting the root element of an XML document:
Element rootElement = document.getRootElement();
- Getting the value of an element:
String elementValue = rootElement.getChildText("element");
- Getting the value of an attribute:
String attributeValue = rootElement.getAttributeValue("attribute");
- 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.