小编典典

如何解析XML以检索嵌入式文本节点

java

我想解析这个XML文件:

要解析的XML文件:

<?xml version="1.0"?>
<Gist xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../schema/Gist.xsd">
    <Name>AbsoluteValue</Name>
    <Description>Determines the absolute value.</Description>
    <PertinentData />
    <Scenarios>
        <Scenario>
            <ID>CALCULATED</ID>
            <Description>The value was used in the absolute value function.</Description>
            <Template>
                <NodeName />
                <Text> is </Text>
                <NodeValue />
                <Text> because it is the absolute value of </Text>
                <InputNameAsLink>Value</InputNameAsLink>
                <Text> (</Text>
                <InputValueAsLink>Value</InputValueAsLink>
                <Text>).</Text>             
            </Template>
        </Scenario>       
        <Scenario>
            <ID>INPUT_IS_BLANK</ID>
            <Description>The value is blank.</Description>
            <Template>
                <NodeName />
                <Text> is blank since </Text>
                <InputNameAsLink>Value</InputNameAsLink>
                <Text> (</Text>
                <InputValueAsLink>Value</InputValueAsLink>
                <Text>) is blank.</Text>
            </Template>
        </Scenario>
    </Scenarios>
</Gist>

我想将要点名称和方案返回给我。因此,对于示例文件,我想要AbsoluteValue和场景列表(CALCULATED和INPUT_IS_BLANK)。如果我错了,请纠正我,但是要使用的数据结构是

Map<String, List<String>>

如何在Java代码中完成此操作?如果可能的话,我想使用XPATH。

我以为这是获取每个SCENARIO的正确XPATH表达式?

/*/Scenarios/Scenario/ID/*

阅读 213

收藏
2020-11-26

共1个答案

小编典典

感谢Marcin Krol,我找到了一个例子并得到了它:

static List<String> parseScenarioByGist() {
    Map<String, List<String>> map = new LinkedHashMap<String, List<String>>();
    String path = "/Users/haddad/development/industry/generalatomics/v1/gists_xml/AbsoluteValue.xml";

    try {
        Document doc = getDocument(path);
        XPathFactory xpathFactory = XPathFactory.newInstance();
        XPath xpath = xpathFactory.newXPath();
        XPathExpression expr = xpath.compile("/*/Scenarios/Scenario/ID");
        NodeList nList = (NodeList) expr.evaluate(doc, XPathConstants.NODESET);
        Integer count = 1;
        List<String> list = new ArrayList<String>();
        for(int i=0;i<nList.getLength();i++) {
            Node n = nList.item(i);
            System.out.println("Node Name: "+n.getTextContent());
            list.add(n.getNodeName());
            count++;
        }
        return list;
    }


    catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (XPathExpressionException e) {
        e.printStackTrace();
    }
    return null;
}

要清理它,但效果很好。

2020-11-26