Javaサンプル XMLタグ・属性表示

import java.io.IOException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.w3c.dom.Attr;
import org.xml.sax.SAXException;

class XMLsample {
public static void main(String[] args) throws Exception {
String filename, tagname, attrname;
XMLReader reader;

filename = args[0];
tagname = args[1];
attrname = "";
if(args.length == 3) {
attrname = args[2];
}
reader = new XMLReader(filename);

reader.getNodeValue(tagname, attrname);

System.exit(0);
}
}

class XMLReader {
private Element rootElement;

XMLReader(String filename) throws IOException, SAXException, ParserConfigurationException {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder documentBuilder = factory.newDocumentBuilder();
Document document = documentBuilder.parse(filename);
rootElement = document.getDocumentElement();
}

public boolean getNodeValue(String tagname, String attrname) {
NodeList nodes = rootElement.getElementsByTagName(tagname);
Element elmt;
Attr attr;

for(int i = 0;i < nodes.getLength();i++) {
System.out.println(getPath(nodes.item(i)));
if(nodes.item(i).getNodeType() == Node.ELEMENT_NODE) {
elmt = (Element)nodes.item(i);
System.out.println("タグ名:" + elmt.getTagName());
System.out.println("要素値:" + elmt.getTextContent());
if(attrname != "") {
if(elmt.hasAttribute(attrname)) {
attr = elmt.getAttributeNode(attrname);
System.out.println("属性名:" + attr.getName());
System.out.println("属性値:" + attr.getValue());
} else {
System.out.println("指定属性無し");
}
}
}
System.out.println("-----QAnon-----");
}

return true;
}

private String getPath(Node node) {
String path = node.getNodeName();
Node parentNode = node.getParentNode();

while(parentNode != null) {
path = parentNode.getNodeName() + "/" + path;
parentNode = parentNode.getParentNode();
}

return path;
}
}