0

次のようなテキストを含むノードを持つxmlファイルを解析しています。

  <?xml version="1.0"  encoding="iso-8859-1"?>
<country>
  <name> France </name>
  <city> Paris </city>
  <region>
    <name> Nord-Pas De Calais </name>
    <population> 3996 </population>
    <city> Lille </city>
  </region>
  <region>
    <name> Valle du Rhone </name>
    <city> Lyon </city>
    <city> Valence </city>
  </region>
</country>

私が取得したいのは、次のような値です。

country -> name.city.region*
region  -> name.(population|epsilon).city*
name    -> epsilon
city    -> epsilon
population -> epsilon

私はそれを行う方法を理解できません

4

1 に答える 1

2

サンプルプログラムを追加しました。同じように読み進めてください。

public class TextXML {

    public static void main(String[] args) {
        try {

            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            DocumentBuilder builder = factory.newDocumentBuilder();
            Document doc = builder.parse(new File("text.xml"));

            // list of country elements
            NodeList listOfCountry = doc.getElementsByTagName("country");
            for (int s = 0; s < listOfCountry.getLength(); s++) {

                Node countyNode = listOfCountry.item(s);

                if (countyNode.getNodeType() == Node.ELEMENT_NODE) {

                    Element countyElement = (Element) countyNode;

                    NodeList nameList = countyElement.getElementsByTagName("name");
                    // we have only one name. Element Tag
                    Element nameElement = (Element) nameList.item(0);
                    System.out.println("Name : " + nameElement.getTextContent());

                    NodeList cityList = countyElement.getElementsByTagName("city");
                    // we have only one name. Element Tag
                    Element cityElement = (Element) cityList.item(0);
                    System.out.println("City : " + cityElement.getTextContent());

                    NodeList regionList = countyElement.getElementsByTagName("region");
                    // we have only one name. Element Tag
                    Element regionElement = (Element) regionList.item(0);
                    System.out.println("Region : " + regionElement.getTextContent());

                    //continue further same way.
                }

            }

        } catch (SAXParseException err) {
            err.printStackTrace();
        } catch (SAXException e) {
            Exception x = e.getException();
            ((x == null) ? e : x).printStackTrace();

        } catch (Throwable t) {
            t.printStackTrace();
        }
    }

}
于 2012-05-01T09:43:15.653 に答える