4

要素とテキストノードをの配列に入れるのを手伝ってくださいString

たとえば、.xmlファイルには次のものがあります。

<soap:Envelope>
  <soap:Body>
    <ser:getTitle>
      <!--Optional:-->
      <ser:title>Meeting</ser:title>
    </ser:getTitle>
    <ser:getDiscription>
      <!--Optional:-->
      <ser:discription>this is the meeting</ser:discription>
    </ser:getDiscription>
    ...
  </soap:Body>
</soap:Envelop>

ここで、値をString[] key, value次のように配置します。

key[0] = "title";
value[0] = "meeting";
key[1] = "discription";
value[1] = "this is the meeting";

... 等々。

よろしくお願いします!

4

1 に答える 1

1

DOMを使用して、入力XMLを解析し、次のようなものを使用できます。

import javax.xml.parsers.*;
import org.w3c.dom.*;
import java.io.File;

public dumpXMLTags(...) {
  String[] keys; // you would need that with appropriate size initialized
  String[] values;  

  // Parse your XML file and construct DOM tree
  File fXmlFile = new File(PATH_TO_YOUR_XML_FILE);
  DocumentBuilder dBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
  Document doc = dBuilder.parse(fXmlFile);
  doc.getDocumentElement().normalize();

  // Traverse DOM tree (make sure is not empty first, etc)
  NodeIterator iterator = traversal.createNodeIterator(
      doc.getDocumentElement(), NodeFilter.SHOW_ELEMENT, null, true);

  int i = 0;  // index to you key/value Array

  for (Node n = iterator.nextNode(); n != null; n = iterator.nextNode()) {
     keys[i] = ((Element) n).getTagName();
     values[i] = ((Element)n).getNodeValue();
     i++;
  }
}

または、XPATHを

//@* | //*[not(*)]

ここで説明する式:質問7199897

public static void main(String[] args) throws Exception {
    DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
    Document doc = builder.parse(new InputSource(new StringReader(xml)));

    XPathFactory xpf = XPathFactory.newInstance();
    XPath xp = xpf.newXPath();
    NodeList nodes = (NodeList)xp.evaluate("//@* | //*[not(*)]", doc, XPathConstants.NODESET);

    System.out.println(nodes.getLength());

    for (int i=0, len=nodes.getLength(); i<len; i++) {
        Node item = nodes.item(i);
        System.out.println(item.getNodeName() + " : " + item.getTextContent());
    }
}
于 2012-08-26T18:46:46.287 に答える