2013-04-16 27 views
0

我需要解析Java中的XML文件,并根据条件检查一些支持。我试着用这个DOM。使用Java解析XML文件

<Config> 
     <Configuration> 
     <Descriptor> 
      <e id="0"> 
      <family>Rest</family> 
      <supportedList> 
       <_length>5</_length> 
       <_type>TypeX[]</_type> 
       <e id="0">value-1</e> 
       <e id="1">value-2</e> 
       <e id="2">value-3</e> 
       <e id="3">value-4</e> 
       <e id="4">value-5</e> 
      </supportedList> 
      </e> 
      <e id="1"> 
      <family>Rest1</family> 
      <supportedList> 
       <_length>5</_length> 
       <_type>TypeX[]</_type> 
       <e id="0">value1-1</e> 
       <e id="1">value1-2</e> 
       <e id="2">value1-3</e> 
       <e id="3">value1-4</e> 
       <e id="4">value1-5</e> 
      </supportedList> 
      </e> 
      </Descriptor> 
     </Configuration> 
    </Config> 

在上面的XML文件,我需要去通过“E”块,然后描述符块,然后搜索家庭 - Rest1然后通过supportedList迭代。检查如果supportedList包含用户提供的值(如果存在),则返回true。

我试过使用DOM解析器,但我无法正确解析文件。我正在处理的实际XML文件是20K行,并且数据太多。任何简单的解决方案。

+1

向我们展示您到目前为止尝试过的方法。 – shakurov

+1

对于这个 – artbristol

+0

,XPath会比DOM更好,实际的文件具有相当敏感的数据,以及我在代码中使用过的相同的东西,因此无法共享代码。 –

回答

0
XPathFactory factory = XPathFactory.newInstance(); 
    XPath xpath = factory.newXPath(); 
    xPathExpression = xpath.compile("//family[text()='Rest1']/e"); 

    NodeList list = (NodeList) xPathExpression 
     .evaluate(xml, XPathConstants.NODESET); 

而在XPath语法上,只需搜索“XPath备忘单”即可。