java dom解析xml

JAVA dom解析XML

public void useDomParseXml() {
		DocumentBuilderFactory domfac = DocumentBuilderFactory.newInstance();
		try {
			DocumentBuilder dombuilder = domfac.newDocumentBuilder();
			InputStream is = new FileInputStream("d:/b.xml");
			Document doc = dombuilder.parse(is);

			Element root = doc.getDocumentElement();
			NodeList books = root.getChildNodes();
			if (books != null) {
				for (int i = 0; i < books.getLength(); i++) {
					Node book = books.item(i);
					if (book.getNodeType() == Node.ELEMENT_NODE) {
						String email = book.getAttributes().getNamedItem("email").getNodeValue();
						System.out.println(email);
						for (Node node = book.getFirstChild(); node != null; node = node
								.getNextSibling()) {
							if (node.getNodeType() == Node.ELEMENT_NODE) {
								if (node.getNodeName().equals("name")) {
									String name = node.getFirstChild().getNodeValue();
									System.out.println(name);
								}

								if (node.getNodeName().equals("price")) {
									String price = node.getFirstChild().getNodeValue();
									System.out.println(price);
								}
							}
						}
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}


你可能感兴趣的:(java dom解析xml)