Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.io.File;
- import java.util.HashMap;
- import java.util.Map;
- import javax.xml.parsers.DocumentBuilder;
- import javax.xml.parsers.DocumentBuilderFactory;
- import javax.xml.xpath.XPath;
- import javax.xml.xpath.XPathConstants;
- import javax.xml.xpath.XPathExpressionException;
- import javax.xml.xpath.XPathFactory;
- import org.w3c.dom.Document;
- import org.w3c.dom.NodeList;
- public class Main {
- public static void main(String[] args) {
- DocumentBuilder builder = null;
- try {
- builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
- }
- catch (Exception e) {
- System.exit(1);
- }
- Document doc = null;
- try {
- doc = builder.parse(new File("shop.xml"));
- }
- catch (Exception e) {
- System.exit(1);
- }
- XPath xpath = XPathFactory.newInstance().newXPath();
- NodeList kind = null;
- try {
- kind =
- (NodeList )xpath.evaluate("//店B/分類[@ID=\"2\"]/商品", doc,
- XPathConstants.NODESET);
- }
- catch (XPathExpressionException e) {
- System.exit(1);
- }
- Map<String, Integer> items = new HashMap<String, Integer>();
- for (int i = 0; i < kind.getLength(); i++) {
- NodeList goods = kind.item(i).getChildNodes();
- String name = null;
- try {
- name =
- ((String )xpath.evaluate("名前", goods, XPathConstants.STRING)).trim();
- }
- catch (Exception e) {
- }
- // String name = goods.item(1).getTextContent().trim();
- int value = 0;
- try {
- value =
- new Integer(((String )xpath.evaluate("価格", goods,
- XPathConstants.STRING)).trim());
- }
- catch (Exception e) {
- }
- items.put(name, value);
- }
- System.out.println(items);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement