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 回答