Advertisement
cd62131

Search XML

Dec 5th, 2013
610
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 5 1.76 KB | None | 0 0
  1. import java.io.File;
  2. import java.util.HashMap;
  3. import java.util.Map;
  4. import javax.xml.parsers.DocumentBuilder;
  5. import javax.xml.parsers.DocumentBuilderFactory;
  6. import javax.xml.xpath.XPath;
  7. import javax.xml.xpath.XPathConstants;
  8. import javax.xml.xpath.XPathExpressionException;
  9. import javax.xml.xpath.XPathFactory;
  10. import org.w3c.dom.Document;
  11. import org.w3c.dom.NodeList;
  12.  
  13. public class Main {
  14.   public static void main(String[] args) {
  15.     DocumentBuilder builder = null;
  16.     try {
  17.       builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
  18.     }
  19.     catch (Exception e) {
  20.       System.exit(1);
  21.     }
  22.     Document doc = null;
  23.     try {
  24.       doc = builder.parse(new File("shop.xml"));
  25.     }
  26.     catch (Exception e) {
  27.       System.exit(1);
  28.     }
  29.     XPath xpath = XPathFactory.newInstance().newXPath();
  30.     NodeList kind = null;
  31.     try {
  32.       kind =
  33.         (NodeList )xpath.evaluate("//店B/分類[@ID=\"2\"]/商品", doc,
  34.           XPathConstants.NODESET);
  35.     }
  36.     catch (XPathExpressionException e) {
  37.       System.exit(1);
  38.     }
  39.     Map<String, Integer> items = new HashMap<String, Integer>();
  40.     for (int i = 0; i < kind.getLength(); i++) {
  41.       NodeList goods = kind.item(i).getChildNodes();
  42.       String name = null;
  43.       try {
  44.         name =
  45.           ((String )xpath.evaluate("名前", goods, XPathConstants.STRING)).trim();
  46.       }
  47.       catch (Exception e) {
  48.       }
  49.       // String name = goods.item(1).getTextContent().trim();
  50.       int value = 0;
  51.       try {
  52.         value =
  53.           new Integer(((String )xpath.evaluate("価格", goods,
  54.             XPathConstants.STRING)).trim());
  55.       }
  56.       catch (Exception e) {
  57.       }
  58.       items.put(name, value);
  59.     }
  60.     System.out.println(items);
  61.   }
  62. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement