我正在解析一个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


我不知道这样做的方法

最佳答案

我添加了一个示例程序。请继续以相同的方式阅读。

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();
        }
    }

}

关于java - 使用从XML文件提取的数据创建正则表达式,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/10395825/

10-10 14:36