JAvaとXml


Javaは主にDOM(最も一般的)、SAX(最も効率的)、XPath(最も直接的)の3つのXMLの解析とノード遍歴モデルを提供している.ここでは,主に2つのモデルDOMとXPathについて実例による一歩一歩理解する.
 1.    最も簡単なXML:

  
  
  
  
  1. //1.  Element TagName( ) 。 
  2.      // Element 。 
  3.      //2.  <RootElement>、<FirstElement> <SecondElement> Element。 
  4.      //3. "I am the first Node" "I am the second Node" Text。 
  5.      // Test.xml  
  6.      //<RootElement> 
  7.      //    <FirstElement>I am the first Node</FirstElement> 
  8.      //    <SecondElement>I am the second Node</SecondElement>     
  9.      //</RootElement> 
  10.      public static void main(String[] args) { 
  11.          //  DocmentBuilderFactory  
  12.          DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); 
  13.          //  DocumentBuilder  
  14.          DocumentBuilder builder = null
  15.          try { 
  16.              builder = factory.newDocumentBuilder(); 
  17.          } catch (ParserConfigurationException e) { 
  18.          } 
  19.          //  Document  
  20.          Document doc = null
  21.          try { 
  22.              doc = builder.parse(new File("D:/test.xml")); 
  23.          } catch (SAXException e) { 
  24.          } catch (IOException e) { 
  25.          } 
  26.   
  27.          NodeList nl = doc.getElementsByTagName("RootElement"); 
  28.          for (int i = 0; i < nl.getLength(); i++) { 
  29.              Element e = (Element) nl.item(i); 
  30.              System.out.println(e.getElementsByTagName("FirstElement").item(0
  31.                      .getFirstChild().getNodeValue()); 
  32.              System.out.println(e.getElementsByTagName("SecondElement"
  33.                      .item(0).getFirstChild().getNodeValue()); 
  34.          } 
  35.      } 
  36.      //1.  Element ,  
  37.      // Element ,  
  38.      // 。 
  39.      //2.  Node (Node ), node.getNodeType() 
  40.      // Node , Node.ELEMENT_NODE、Node.ATTRIBUTE_NODE 。 
  41.      // Test.xml  
  42.      //<RootElement> 
  43.      //    <FirstElement>I am the first Node</FirstElement> 
  44.      //    <SecondElement>I am the second Node</SecondElement>     
  45.      //</RootElement> 
  46.      public static void main(String[] args) { 
  47.          String filename = "D:/Test.xml"
  48.          try { 
  49.              System.out.println(filename + " elementCount: " + getElementCount(filename)); 
  50.          } catch (Exception e) { 
  51.          } 
  52.      } 
  53.      /*   getElementCount(Node),Node  */ 
  54.      public static int getElementCount(String fileName) throws Exception { 
  55.          Node node = readFile(new File(fileName)); 
  56.          return getElementCount(node); //  Elements 
  57.      } 
  58.      /*  ,  Document */ 
  59.      public static Document readFile(File file) throws Exception { 
  60.          Document doc; 
  61.          try { 
  62.              /*   DocumentBuilderFactory   */ 
  63.              DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); 
  64.              /*   DocumentBuilder   */ 
  65.              DocumentBuilder db = dbf.newDocumentBuilder(); 
  66.              /*   */ 
  67.              doc = db.parse(file); 
  68.              /*   Document   */ 
  69.              return doc; 
  70.          } catch (SAXParseException ex) { 
  71.              throw (ex); 
  72.          } catch (SAXException ex) { 
  73.              Exception x = ex.getException(); // get underlying Exception 
  74.              throw ((x == null) ? ex : x); 
  75.          } 
  76.      } 
  77.      /* 
  78.       *  DOM  ELEMENTS 
  79.       */ 
  80.      public static int getElementCount(Node node) { 
  81.          /*  node , 0 */ 
  82.          if (null == node) 
  83.              return 0
  84.          int sum = 0
  85.          //  , , ELEMENT 
  86.          boolean isElement = (node.getNodeType() == Node.ELEMENT_NODE); 
  87.          //  ELEMENT , sum 1 
  88.          if (isElement) 
  89.              sum = 1
  90.          //   
  91.          NodeList children = node.getChildNodes(); 
  92.          //  ,  
  93.          if (null == children) 
  94.              return sum; 
  95.          //   
  96.          for (int i = 0; i < children.getLength(); i++) 
  97.              sum += getElementCount(children.item(i)); 
  98.          return sum; 
  99.      } 

  2.    DOMモデルを介してXMLのすべてのノードを比較的完全に巡回する例:

  
  
  
  
  1. public class MyTest { 
  2.          //  
  3.          // , hardcode, XML 。 
  4.          //<attributes> 
  5.          //    <!--Comment1--> 
  6.          //    <attribute1 name="Technology" type="C" size="100" allow_multi_val="N" /> 
  7.          //    <attribute2 name="Mfg_Area" type="C" size="100" allow_multi_val="N" /> 
  8.          //    <attribute3 name="Product_Family" type="C" size="100" allow_multi_val="N"/> 
  9.          //    <![CDATA[ cdatatest1 ]]> 
  10.          //    <attributeWithText>This is test data</attributeWithText> 
  11.          //</attributes> 
  12.          public static void main(String[] args) { 
  13.              DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); 
  14.              factory.setIgnoringElementContentWhitespace(true); 
  15.              //  DocumentBuilder  
  16.              DocumentBuilder builder = null
  17.              try { 
  18.                  builder = factory.newDocumentBuilder(); 
  19.              } catch (ParserConfigurationException e) { 
  20.              } 
  21.              ByteArrayOutputStream bout = new ByteArrayOutputStream(512); 
  22.              PrintStream ps = new PrintStream(bout); 
  23.              ps.println("<attributes>"); 
  24.              ps.println("<!--Comment1-->"); 
  25.              ps.println("<![CDATA[ cdatatest1 ]]>"); 
  26.              ps.println("<attribute1 name=\"Technology\" type=\"C\" " + 
  27.                      "size=\"100\" isnull=\"true\" allow_multi_val=\"N\" />"); 
  28.              ps.println("<attribute2 name=\"Mfg_Area\" type=\"C\" " + 
  29.                      "size=\"100\" isnull=\"true\" allow_multi_val=\"N\" />"); 
  30.              ps.println("<attribute3 name=\"Product_Family\" type=\"C\" " + 
  31.                      "size=\"100\" isnull=\"true\" allow_multi_val=\"N\" />"); 
  32.              ps.println("<attributeWithText>This is test data</attributeWithText>"); 
  33.              ps.print("</attributes>"); 
  34.              ps.flush(); 
  35.              ByteArrayInputStream bin = new ByteArrayInputStream(bout.toByteArray()); 
  36.              //  Document  
  37.              try { 
  38.                  doc = builder.parse(bin); 
  39.              } catch (SAXException e) { 
  40.                  e.printStackTrace(); 
  41.              } catch (IOException e) { 
  42.              } 
  43.              // 1.   
  44.              Element rootElement = doc.getDocumentElement(); 
  45.              printElement(rootElement); 
  46.              System.out.printf("</%s>",rootElement.getTagName()); 
  47.          } 
  48.          static void printIndent() { 
  49.              for (int i = 0; i < indentLevel; ++i) 
  50.                  System.out.print("\t"); 
  51.          } 
  52.          static void printElement(Element element) { 
  53.              printIndent(); 
  54.              System.out.printf("<%s",element.getTagName()); 
  55.              // Attribute Map , AtrributeName 。 
  56.              //5.  , Element  
  57.              NamedNodeMap nodeMap = element.getAttributes(); 
  58.              for (int i = 0; i < nodeMap.getLength(); ++i) { 
  59.                  Node node = nodeMap.item(i); 
  60.                  if (i == 0
  61.                      System.out.print(" "); 
  62.                  //6.  Name Value。 
  63.                  System.out.printf("%s = %s ", node.getNodeName(), node.getNodeValue()); 
  64.                  if (i == nodeMap.getLength() - 1
  65.                      System.out.print(" />"); 
  66.              } 
  67.              String text = element.getTextContent(); 
  68.              if (nodeMap.getLength() == 0
  69.                  System.out.print(">"); 
  70.              if (element != doc.getDocumentElement()) { 
  71.                  if (!text.trim().isEmpty()) { 
  72.                      System.out.print(text); 
  73.                      System.out.printf("</%s>",element.getTagName()); 
  74.                  } 
  75.              } 
  76.              System.out.println(); 
  77.              // 2.   
  78.              NodeList nodeList = element.getChildNodes(); 
  79.              indentLevel++; 
  80.              for (int i = 0; i < nodeList.getLength(); ++i) { 
  81.                  // 3.   
  82.                  Node node = nodeList.item(i); 
  83.                  // 4.   
  84.                  if (node.getNodeType() == Node.ELEMENT_NODE) { 
  85.                      printElement((Element) node); 
  86.                  } else { 
  87.                      printOtherNode(node); 
  88.                  } 
  89.              } 
  90.              indentLevel--; 
  91.          } 
  92.          static void printOtherNode(Node node) { 
  93.              if (node.getNodeType() == Node.COMMENT_NODE) { 
  94.                  printIndent(); 
  95.                  System.out.printf("<!--%s-->
    "
    ,node.getNodeName()); 
  96.              } else if (node.getNodeType() == Node.CDATA_SECTION_NODE) { 
  97.                  printIndent(); 
  98.                  System.out.printf("<![CDATA[ %s ]]>
    "
    ,node.getNodeName()); 
  99.              } 
  100.          } 
  101.          private static Document doc; 
  102.          private static int indentLevel = 0
  103.      } 

3.    XMLのノードにアクセスするには、XPathを使用します.    XPath言語の基本的な構文は次のとおりです.    1)   /gridbag/row:ルート要素gridbagのサブ要素のすべてのrow要素を表します.    2)   /gridbag/row[1]:[]を使用して、最初のサブエレメントを選択するエレメントのセットの特定のエレメントを選択します.    3)   /gridbag/row[1]/cell[1]/@anchor:最初の行の最初のセルのanchorプロパティを説明します.    4)   /gridbag/row/cell/@anchor:ルート要素gridbagのサブ要素である行要素のすべてのセルのanchorプロパティノードを記述します.    5)    count(/gridbag/row):XPathはcountなどの有用な関数も提供します.    Java SE 5にAPIを追加してXPath式を計算するには、XPathFactoryからXPathオブジェクトを作成する必要があります.たとえば、次のようにします.    XPathFactory xpFactory = XPathFactory.newInstance();     XPath path = xpFactory.newXPath();     次にevaluateメソッドを呼び出してXPath式を計算します.たとえば、次のようになります.      String username = path.evaluate("/gridbag/row[1]/@anthor",doc);     この形式のevaluate()メソッドは、文字列を返します.また、次のようなサブノードのセットを返します.    NodeList nodes = path.evaluate("/gridbag/row",doc,XPathConstants.NODESET);     ノードが1つしかない場合は、次のようにNODESETの代わりにNODE定数を使用できます.    Node node = path.evaluate("/gridbag/row[1]",doc,XPathConstants.NODE);     結果が数値の場合は、次のようなXPathConstants.NUMBERを使用します.    int count = ((Number)path.evaluate("count(/gridbag/row)",doc,XPathConstants.NUMBER)).intValue();     次のコードは、XPathクエリXMLに基づいて一般的に使用されているコードのみをリストします.

  
  
  
  
  1. public class MyTest { 
  2.          //    <projects> 
  3.          //        <project id = "BP001"> 
  4.          //            <name>Banking Project</name> 
  5.          //            <start-date>Jan 10 1999</start-date> 
  6.          //            <end-date>Jan 10 2003</end-date> 
  7.          //        </project> 
  8.          //        <project id = "TP001">         
  9.          //            <name>Telecommunication Project</name> 
  10.          //            <start-date>March 20 1999</start-date> 
  11.          //            <end-date>July 30 2004</end-date> 
  12.          //        </project> 
  13.          //        <project id = "PP001"> 
  14.          //            <name>Portal Project</name> 
  15.          //            <start-date>Dec 10 1998</start-date> 
  16.          //            <end-date>March 10 2006</end-date> 
  17.          //        </project> 
  18.          //    </projects> 
  19.          public static void main(String[] args) { 
  20.              XPathReader reader = new XPathReader("D:/Test.xml"); 
  21.              // projects project id 。 
  22.              String expression = "/projects/project[1]/@id"
  23.              System.out.println(reader.read(expression, XPathConstants.STRING)); 
  24.              // projects project name  
  25.              expression = "/projects/project[2]/name"
  26.              System.out.println(reader.read(expression, XPathConstants.STRING)); 
  27.              // project , , name , 
  28.              // name Telecommunication Project, name  
  29.              //project xpath , name 。 
  30.              expression = "//project[name=\"Telecommunication Project\"]/name"
  31.              System.out.println(reader.read(expression, XPathConstants.STRING)); 
  32.              // projects project  
  33.              expression = "/projects/project[3]"
  34.              NodeList thirdProject = (NodeList) reader.read(expression, XPathConstants.NODESET); 
  35.              traverse(thirdProject); 
  36.          } 
  37.       
  38.          private static void traverse(NodeList rootNode) { 
  39.              for (int index = 0; index < rootNode.getLength(); index++) { 
  40.                  Node aNode = rootNode.item(index); 
  41.                  if (aNode.getNodeType() == Node.ELEMENT_NODE) { 
  42.                      NodeList childNodes = aNode.getChildNodes(); 
  43.                      if (childNodes.getLength() > 0) { 
  44.                          System.out.println("Name:" + aNode.getNodeName() + ",Value:" 
  45.                                  + aNode.getTextContent()); 
  46.                      } 
  47.                      traverse(aNode.getChildNodes()); 
  48.                  } 
  49.              } 
  50.          } 
  51.      } 
  52.       
  53.      class XPathReader { 
  54.          private String xmlFile; 
  55.          private Document xmlDocument; 
  56.          private XPath xPath; 
  57.          public XPathReader(String xmlFile) { 
  58.              this.xmlFile = xmlFile; 
  59.              initObjects(); 
  60.          } 
  61.          private void initObjects() { 
  62.              try { 
  63.                  // XML DOM , 。 
  64.                  xmlDocument = DocumentBuilderFactory.newInstance() 
  65.                      .newDocumentBuilder().parse(xmlFile); 
  66.                  // XPath  
  67.                  xPath = XPathFactory.newInstance().newXPath(); 
  68.              } catch (IOException ex) { 
  69.              } catch (SAXException ex) { 
  70.              } catch (ParserConfigurationException ex) { 
  71.              } 
  72.          } 
  73.          public Object read(String expression, QName returnType) { 
  74.              try { 
  75.                  // , 。 
  76.                  XPathExpression xPathExpression = xPath.compile(expression); 
  77.                  //returnType evaluate 。 
  78.                  return xPathExpression.evaluate(xmlDocument, returnType); 
  79.              } catch (XPathExpressionException ex) { 
  80.                  return null
  81.              } 
  82.          } 
  83.      } 

    4.    XMLのDOMモデルを構築し、DOMTreeModelをXMLファイルに出力します.

  
  
  
  
  1. public class MyTest { 
  2.          public static void main(String[] args) { 
  3.              DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); 
  4.              Element root = null, attr = null,subAttr = null
  5.              try { 
  6.                  factory.setIgnoringElementContentWhitespace(true); 
  7.                  DocumentBuilder db = factory.newDocumentBuilder(); 
  8.                  Document xmldoc = db.parse(new File("D:/Test.xml")); 
  9.                  root = xmldoc.getDocumentElement(); 
  10.                  //1.  DOMTreeModel  
  11.                  // Element 
  12.                  attr = xmldoc.createElement("attribute4"); 
  13.                  subAttr = xmldoc.createElement("subAttribute"); 
  14.                  // Element  
  15.                  subAttr.setTextContent("Hello, I am sub-attribute."); 
  16.                  attr.appendChild(subAttr); 
  17.                  // Element  
  18.                  attr.setAttribute("attrFirstName""attrFirstValue"); 
  19.                  root.appendChild(attr); 
  20.                  output(xmldoc, null); 
  21.                  output(xmldoc, "D:/Test1_Edited.xml"); 
  22.                  // xpath 。 
  23.                  attr = (Element)selectSingleNode("/attributes/attribute3",root); 
  24.                  //  
  25.                  attr.getAttributeNode("name").setNodeValue("Hello"); 
  26.                  output(attr,null); 
  27.                  root.getElementsByTagName("attribute3").item(1).setTextContent("This is other test"); 
  28.                  output(root,null); 
  29.                  //  
  30.                  root.removeChild(root.getElementsByTagName("attributeWithText").item(0)); 
  31.                  output(root,null); 
  32.                  // xpath ,  
  33.                  NodeList attrs = selectNodes("/attributes/attribute3", root); 
  34.                  for (int i = 0; i < attrs.getLength(); ++i) 
  35.                      attrs.item(i).getParentNode().removeChild(attrs.item(i)); 
  36.                  root.normalize(); 
  37.                  output(root,null); 
  38.              } catch (ParserConfigurationException e) { 
  39.              } catch (SAXException e) { 
  40.              } catch (IOException e) { 
  41.              } 
  42.          } 
  43.       
  44.          public static void output(Node node, String filename) { 
  45.              TransformerFactory transFactory = TransformerFactory.newInstance(); 
  46.              try { 
  47.                  Transformer transformer = transFactory.newTransformer(); 
  48.                  //   
  49.                  transformer.setOutputProperty("encoding""gb2312"); 
  50.                  transformer.setOutputProperty("indent""yes"); 
  51.                  DOMSource source = new DOMSource(); 
  52.                  //  DOM (holder) 
  53.                  source.setNode(node); 
  54.                  StreamResult result = new StreamResult(); 
  55.                  if (filename == null) { 
  56.                      //  transformer  
  57.                      result.setOutputStream(System.out); 
  58.                  } else { 
  59.                      result.setOutputStream(new FileOutputStream(filename)); 
  60.                  } 
  61.                  //   
  62.                  transformer.transform(source, result); 
  63.              } catch (TransformerConfigurationException e) { 
  64.              } catch (TransformerException e) { 
  65.              } catch (FileNotFoundException e) { 
  66.              } 
  67.          } 
  68.       
  69.          public static Node selectSingleNode(String express, Object source) { 
  70.              Node result = null
  71.              XPathFactory xpathFactory = XPathFactory.newInstance(); 
  72.              XPath xpath = xpathFactory.newXPath(); 
  73.              try { 
  74.                  // xpath , compile 。 
  75.                  result = (Node) xpath.evaluate(express, source, XPathConstants.NODE); 
  76.              } catch (XPathExpressionException e) { 
  77.              } 
  78.              return result; 
  79.          } 
  80.       
  81.          public static NodeList selectNodes(String express, Object source) {82             NodeList result = null
  82.              XPathFactory xpathFactory = XPathFactory.newInstance(); 
  83.              XPath xpath = xpathFactory.newXPath(); 
  84.              try { 
  85.                  result = (NodeList) xpath.evaluate(express, source, XPathConstants.NODESET); 
  86.              } catch (XPathExpressionException e) { 
  87.              } 
  88.              return result; 
  89.          } 
  90.      }