2012-05-01 91 views
0

我解析XML文件,有节点用这样的文本中提取数据的正则表达式:创建使用从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 

我找不出一种方法来做到这一点

+0

@SalmanA你看不到的问题,即时通讯使用JDOM解析器解析我的XML文件,我希望得到的正则表达式联想到XML文件 –

+0

@his我不是一个正则表达式解析XML文件,我想生成正则表达式 –

+0

你想创建语法吗?像DTD或XSD一样? –

回答

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

} 
+0

什么如果我有一个长文件 –

+0

,你将不得不测试你的自我。 –

+0

您也可以尝试使用JAXB。这是从XML内容读取数据的好方法。 –