简体   繁体   English

如何通过XPATH解析XML文件

[英]How to Parse XML file via XPATH

I'd like to parse this XML file: 我想解析这个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>

To get me that value at this XPATH /Gist/Name, so for this file it would be a String: 为了在此XPATH / Gist / Name处获取该值,因此对于该文件,它将是一个String:

  • AboveOrEqualToThreshold 高于或等于阈值

and the scenarios for this file at this XPATH Gist/Scenarios/Scenario/ID/*, so for this file it would be a list of Strings: 以及此文件在XPATH Gist / Scenarios / Scenario / ID / *下的方案,因此对于此文件,它将是字符串列表:

  • THRESHOLD_DOES_NOT_APPLY THRESHOLD_DOES_NOT_APPLY

  • ABOVE_THRESHOLD ABOVE_THRESHOLD

  • EQUAL_TO_THRESHOLD EQUAL_TO_THRESHOLD

  • NOT_ABOVE_THRESHOLD NOT_ABOVE_THRESHOLD

So the data structure for this would be: 因此,其数据结构为:

Map<String,List<String>>

How can I accomplish this in Java, this seems pretty straight forward but I am unsuccess in my attempts to get this. 我该如何用Java完成这项工作,这似乎很简单,但是我尝试获得此目标并没有成功。

Any help or assistance would be much appreciated. 任何帮助或协助将不胜感激。

My implementation attempt: 我的实现尝试:

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

I am assuming when you say you need the output as 我假设当你说你需要输出为

Map<String, List<String>>

you mean 你的意思是

Map<Name, List<Scenarios>>

(correct me if I am wrong!!!). (如果我错了,请纠正我!!!)。 I have written something on the basis of that using the Conversion Box . 我已经使用Conversion Box在此基础上写了一些东西。 Have a look .... 看一看 ....

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

Output: 输出:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM