Accessing XML Elements and Attributes
Once you have parsed an XML document, you can access its elements and attributes using the appropriate methods provided by the Java XML parsing APIs. Here's how you can do it using the DOM and SAX parsers.
Accessing Elements with the DOM Parser
To access elements in an XML document using the DOM parser, you can use the getElementsByTagName()
method to retrieve a list of elements with a specific tag name, and then iterate over the list to access the individual elements.
// Assuming you have already parsed the XML document using the DOM parser
Element root = document.getDocumentElement();
NodeList elements = root.getElementsByTagName("book");
for (int i = 0; i < elements.getLength(); i++) {
Element book = (Element) elements.item(i);
String title = book.getElementsByTagName("title").item(0).getTextContent();
String author = book.getElementsByTagName("author").item(0).getTextContent();
System.out.println("Title: " + title);
System.out.println("Author: " + author);
}
Accessing Attributes with the DOM Parser
To access attributes of an XML element using the DOM parser, you can use the getAttribute()
method.
// Assuming you have already parsed the XML document using the DOM parser
Element book = (Element) elements.item(0);
String id = book.getAttribute("id");
System.out.println("Book ID: " + id);
Accessing Elements and Attributes with the SAX Parser
When using the SAX parser, you can access elements and attributes in the startElement()
and endElement()
methods of your custom DefaultHandler
implementation.
private static class MyHandler extends DefaultHandler {
private String currentElement;
@Override
public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
currentElement = qName;
if (qName.equals("book")) {
String id = attributes.getValue("id");
System.out.println("Book ID: " + id);
}
}
@Override
public void endElement(String uri, String localName, String qName) throws SAXException {
if (qName.equals("title")) {
System.out.println("Title: " + currentElementValue);
} else if (qName.equals("author")) {
System.out.println("Author: " + currentElementValue);
}
currentElement = null;
}
@Override
public void characters(char[] ch, int start, int length) throws SAXException {
if (currentElement != null) {
currentElementValue = new String(ch, start, length);
}
}
}
Both the DOM and SAX parsers provide ways to access the elements and attributes of an XML document. The choice between the two depends on the specific requirements of your application, such as the size of the XML document and the level of manipulation required.