Java HTML/XML - 如何使用DOM解析器解析XML文檔,每個標(biāo)記有多個元素
我們想知道如何使用DOM解析器解析XML文檔,每個標(biāo)記有多個元素。
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathFactory;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
public class Main {
public static void main(String[] args) throws Exception {
XPathFactory xpf = XPathFactory.newInstance();
XPath xPath = xpf.newXPath();
XPathExpression schoolNameExpression = xPath.compile("SchoolName");
XPathExpression classNameExpression = xPath
.compile("Classes/Class/ClassName");
InputSource inputSource = new InputSource("input.xml");
NodeList schoolNodes = (NodeList) xPath.evaluate("/Data/Schools/School",
inputSource, XPathConstants.NODESET);
for (int x = 0; x < schoolNodes.getLength(); x++) {
Node schoolElement = schoolNodes.item(x);
System.out.println(schoolNameExpression.evaluate(schoolElement,
XPathConstants.STRING));
NodeList classNames = (NodeList) classNameExpression.evaluate(
schoolElement, XPathConstants.NODESET);
for (int y = 0; y < classNames.getLength(); y++) {
System.out.println(classNames.item(y).getTextContent());
}
}
}
}