Create a regular expression using data extracted from an XML file

☆樱花仙子☆ 提交于 2019-12-25 00:22:59

问题


I'm parsing an xml file, that has nodes with text like this:

  <?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>

What I want to get is values like this:

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

I can't figure out a method to do that


回答1:


I have added a sample program. Please continue with reading same way.

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

}


来源:https://stackoverflow.com/questions/10395825/create-a-regular-expression-using-data-extracted-from-an-xml-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!