| ページ一覧 | ブログ | twitter |  書式 | 書式(表) |

MyMemoWiki

Java XPath

提供: MyMemoWiki
2020年2月15日 (土) 07:33時点におけるPiroto (トーク | 投稿記録)による版 (ページの作成:「http://www.atmarkit.co.jp/fxml/ddd/ddd001/ddd001-namespaces1.html XMLを返すurlからXMLデータを取得、解析し、Nodeのリストを作成する。 URLConne…」)
(差分) ← 古い版 | 最新版 (差分) | 新しい版 → (差分)
ナビゲーションに移動 検索に移動

http://www.atmarkit.co.jp/fxml/ddd/ddd001/ddd001-namespaces1.html XMLを返すurlからXMLデータを取得、解析し、Nodeのリストを作成する。

  1. URLConnection conn = (new URL(url)).openConnection();
  2. conn.connect();
  3.  
  4. InputSource in = new InputSource(new InputStreamReader(conn.getInputStream()));
  5. XPathFactory xfactory = XPathFactory.newInstance();
  6. XPath xpath = xfactory.newXPath();
  7.  
  8. NodeList result = (NodeList)xpath.evaluate("//*[local-name()='Parameter']/text()", in, XPathConstants.NODESET);
  9.  
  10. for (int i=0; i<result.getLength(); i++) {
  11. System.out.println(result.item(i).toString());
  12. }


  1. package generate;
  2.  
  3. import java.util.Collections;
  4. import java.util.HashMap;
  5. import java.util.HashSet;
  6. import java.util.Iterator;
  7. import java.util.Map;
  8. import java.util.Set;
  9.  
  10. import javax.xml.XMLConstants;
  11. import javax.xml.namespace.NamespaceContext;
  12.  
  13. public class NameSpaceContextImpl implements NamespaceContext {
  14.  
  15. Map<String, String> map = new HashMap<String, String>();
  16. public NameSpaceContextImpl() {
  17. setNamespaceURI(XMLConstants.DEFAULT_NS_PREFIX, XMLConstants.NULL_NS_URI);
  18. setNamespaceURI(XMLConstants.XML_NS_PREFIX, XMLConstants.XML_NS_URI);
  19. setNamespaceURI(XMLConstants.XMLNS_ATTRIBUTE, XMLConstants.XMLNS_ATTRIBUTE_NS_URI);
  20. }
  21. public void setNamespaceURI(String prefix, String uri) {
  22. map.put(prefix, uri);
  23. }
  24. public String getNamespaceURI(String prefix) {
  25. return map.get(prefix);
  26. }
  27.  
  28. public String getPrefix(String namespaceURI) {
  29. if (namespaceURI == null) {
  30. throw new IllegalArgumentException();
  31. }
  32. Set<Map.Entry<String, String>>set = map.entrySet();
  33. for (Map.Entry<String, String>item : set) {
  34. if (namespaceURI.equals(item.getValue())) {
  35. return item.getKey();
  36. }
  37. }
  38. return XMLConstants.NULL_NS_URI;
  39. }
  40.  
  41. public Iterator getPrefixes(String namespaceURI) {
  42. Set<String> prefixes = new HashSet<String>();
  43. Set<Map.Entry<String, String>>set = map.entrySet();
  44. for (Map.Entry<String, String>item : set) {
  45. if (namespaceURI.equals(item.getValue())) {
  46. prefixes.add(item.getKey());
  47. }
  48. }
  49. return Collections.unmodifiableCollection(prefixes).iterator();
  50. }
  51.  
  52. }