2015-10-01 2 views
0

Я хотел бы разобрать этот XML-файл:Как Разобрать файл XML с помощью XPATH

<?xml version="1.0"?> 
<Gist xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../schema/Gist.xsd"> 
    <Name>AboveOrEqualToThreshold</Name> 
    <Version>1</Version> 
    <Tags> 
     <Tag>Comparison</Tag> 
    </Tags> 
    <Description>Determines if a value is at or over a threshold or not.</Description> 
    <Configuration /> 
    <OutputType> 
     <ScalarType>Boolean</ScalarType> 
    </OutputType> 
    <PertinentData> 
     <Item> 
      <Name>ValueMinusThreshold</Name> 
     </Item> 
     <Item> 
      <Name>ThresholdMinusValue</Name> 
     </Item> 
    </PertinentData> 
    <Scenarios> 
     <Scenario> 
      <ID>THRESHOLD_DOES_NOT_APPLY</ID> 
      <Description>The threshold does not apply.</Description> 
     </Scenario> 
     <Scenario> 
      <ID>ABOVE_THRESHOLD</ID> 
      <Description>The value is above the threshold.</Description> 
     </Scenario> 
     <Scenario> 
      <ID>EQUAL_TO_THRESHOLD</ID> 
      <Description>The value is equal to the threshold.</Description> 
     </Scenario> 
     <Scenario> 
      <ID>NOT_ABOVE_THRESHOLD</ID> 
      <Description>The value is not above the threshold.</Description> 
     </Scenario> 
    </Scenarios> 
</Gist> 

Чтобы получить меня, что значение в этом XPATH/Gist/Name, поэтому для этого файла было бы быть строка:

  • AboveOrEqualToThreshold

и сценарии для этого файла в этом XPATH Gist/сценарии/сценарий/ID/*, поэтому для этого файла было бы список строк:

  • THRESHOLD_DOES_NOT_APPLY

  • above_threshold

  • EQUAL_TO_THRESHOLD

  • NOT_ABOVE_THRESHOLD

Так структура данных для этого было бы:

Map<String,List<String>> 

Как это сделать в Java, это выглядит довольно прямолинейно, но я не уверен в своих попытках получить это.

Любая помощь или помощь будут высоко оценены.

Моя реализация попытка:

static Map<Node, Node> parseScenarioByGist(String filename) throws IOException, XPathException { 

    XPath xpath = XPathFactory.newInstance().newXPath(); 
    Map<Node, Node> scenarioByGist = new LinkedHashMap<Node, Node>(); 

    try (InputStream file = new BufferedInputStream(Files.newInputStream(Paths.get(filename)))) { 

     NodeList nodes = (NodeList) xpath.evaluate("//Gist", new InputSource(file), XPathConstants.NODESET); 
     int nodeCount = nodes.getLength(); 

     for (int i = 0; i < nodeCount; i++) { 
      Node node = nodes.item(i); 


      Node gist = (Node) xpath.evaluate("Gist/Name", node, XPathConstants.NODE);//String node.getAttributes().getNamedItem("name").getNodeValue(); 
      Node scenario = (Node) xpath.evaluate("Gist/Scenarios/Scenario/ID/*", node, XPathConstants.NODE); 

      scenarioByGist.put(gist, scenario); 
     } 
    } 

    return scenarioByGist; 
} 

ответ

1

Я предполагаю, что когда вы говорите, что нужен выход, как

Map<String, List<String>> 

вы имеете в виду

Map<Name, List<Scenarios>> 

(поправьте меня, если я не прав! !!). Я написал что-то на основе этого, используя Conversion Box. Посмотрите ....

import java.util.ArrayList; 
import java.util.HashMap; 
import java.util.List; 
import java.util.Map; 

import cjm.component.cb.map.ToMap; 

public class DummyClass 
{ 
public static void main(String[] args) 
{ 
    try 
    { 
     String xml = "<?xml version=\"1.0\"?><Gist xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:noNamespaceSchemaLocation=\"../schema/Gist.xsd\"><Name>AboveOrEqualToThreshold</Name><Version>1</Version><Tags><Tag>Comparison</Tag></Tags><Description>Determines if a value is at or over a threshold or not.</Description><Configuration /><OutputType><ScalarType>Boolean</ScalarType></OutputType><PertinentData><Item><Name>ValueMinusThreshold</Name></Item><Item><Name>ThresholdMinusValue</Name></Item></PertinentData><Scenarios><Scenario><ID>THRESHOLD_DOES_NOT_APPLY</ID><Description>The threshold does not apply.</Description></Scenario><Scenario><ID>ABOVE_THRESHOLD</ID><Description>The value is above the threshold.</Description></Scenario><Scenario><ID>EQUAL_TO_THRESHOLD</ID><Description>The value is equal to the threshold.</Description></Scenario><Scenario><ID>NOT_ABOVE_THRESHOLD</ID><Description>The value is not above the threshold.</Description></Scenario></Scenarios></Gist>"; 

     Map<String, Object> map = (new ToMap()).convertToMap(xml); // Conversion Box 

     Map<String, Object> mapGist = (Map<String, Object>) map.get("Gist"); 

     String name = (String) mapGist.get("Name"); 

     List<Map<String, Object>> scenarioMapList = (List<Map<String, Object>>) mapGist.get("Scenarios"); 

     List<String> scenarioList = new ArrayList<String>(); 

     for (int index = 0; index < scenarioMapList.size(); index++) 
     { 
      Map<String, Object> scenarioMap = scenarioMapList.get(index); 

      scenarioList.add((String) scenarioMap.get("ID")); 
     } 

     Map<String, List<String>> whatMosawiWants = new HashMap<String, List<String>>(); 

     whatMosawiWants.put(name, scenarioList); 

     System.out.println("What Mosawi wants: " + whatMosawiWants); 
    } 
    catch (Exception e) 
    { 
     e.printStackTrace(); 
    } 
} 
} 

Выход:

-------- XML Detected -------- 
-------- Map created Successfully -------- 
What Mosawi wants: {AboveOrEqualToThreshold=[THRESHOLD_DOES_NOT_APPLY, ABOVE_THRESHOLD, EQUAL_TO_THRESHOLD, NOT_ABOVE_THRESHOLD]} 
+0

Я был в состоянии получить мой работает, но используя другую реализацию, но у вас хорошо работает слишком! благодаря – mosawi

Смежные вопросы