java - 如何通过 XPATH 解析 XML 文件

标签 java xml parsing xpath

我想解析这个 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>

要获取此 XPATH/Gist/Name 处的值,因此对于此文件,它将是一个字符串:

  • 高于或等于阈值

以及此文件的场景位于此 XPATH Gist/Scenarios/Scenario/ID/*,因此对于此文件来说,它将是一个字符串列表:

  • THRESHOLD_DOES_NOT_APPLY

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

最佳答案

我假设当你说你需要输出时

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

关于java - 如何通过 XPATH 解析 XML 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32895249/

相关文章:

在android中创建警报对话框时出现java.lang.IllegalStateException

java - 没有 pull 的Git推送

Java-EE session 澄清

python - 重新初始化 PLY 解析器

java - java中从字符串中获取元素的快速方法

javascript - marklogic 使用 node-client-api 保存 xml 文档?

python - 如何使用 pandas 将 xml 转换为 dataFrame

android - 在 Android 中从 res/xml 打开 XML 文件

c# - 词法分析器和解析器之间的通信

xml - Scala 解析器组合器解析 xml?