java - 在 Java 中使用 XPath 解析 XML

标签 java xml xpath

我想解析这个 XML 文件:

 <NameDefinitions xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:noNamespaceSchemaLocation="../Documents/Calcs/FriendlyNames.xsd">


     <NameDefinition>
         <ID>/Temporary/EIC/EICWorksheetPP/WagesLessThanAdjustments</ID>
         <Name>you have more income that doesn't count than income that counts</Name>
         <BooleanPhrases>
             <True><Text>you have more income that doesn't count than income that counts</Text></True>
             <False><Text>you have more income that counts than income that doesn't count</Text></False>
             <Blank><Text>we don't if you have more income that doesn't count than income that counts</Text></Blank>
         </BooleanPhrases>
         <BooleanQuestions>
             <True><Text>Why do I have more income that doesn't count than income that counts?</Text></True>
             <False><Text>Why do I have more income that counts than income that doesn't count?</Text></False>
             <Blank><Text>Why don't you know if I have more income that doesn't count than income that counts?</Text></Blank>
         </BooleanQuestions>
     </NameDefinition>


     <NameDefinition>
         <ID>/Temporary/EIC/HaveInaccurateInfo</ID>
         <Name>you told us your info is incorrect</Name>
         <BooleanPhrases>
             <True><Text>you told us some of your info is incorrect</Text></True>
             <False><Text>you told us your info is correct</Text></False>
             <Blank><Text>we don't know whether your info is correct</Text></Blank>
         </BooleanPhrases>
         <BooleanQuestions>
             <True><Text>Why is some of my info incorrect?</Text></True>
             <False><Text>Why is my info correct?</Text></False>
             <Blank><Text>Why don't you know if my info is correct?</Text></Blank>
         </BooleanQuestions>
     </NameDefinition>

</NameDefinitions>

获取IDName节点的值。我想要返回的数据结构是 Map(String,String) 因此 ID 是键,Name 是值。

如何在 Java 6 中实现此目的?

编辑:

但是,这是我当前的实现

static Map<String, String> parse(String pathToFriendlyNamesFile) 
        throws IOException, 
        XPathExpressionException { 

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

    InputStream file = null;

    try {
        file = new BufferedInputStream(Files.newInputStream(Paths.get(pathToFriendlyNamesFile)));
        InputSource inputSource = new InputSource(file);

        NodeList nodeIDList = (NodeList) xpath.evaluate("//NameDefinition/ID", inputSource, XPathConstants.NODESET);
        NodeList nodeNameList = (NodeList) xpath.evaluate("//NameDefinition/Name", inputSource, XPathConstants.NODESET);

        int nodeCount = nodeIDList.getLength();
        System.out.println("Node count: "+nodeCount);
        for(int i=0;i<nodeCount;i++) {

            Node nodeID = nodeIDList.item(i);
            Node nodeName = nodeNameList.item(i);

            String id = nodeID.getTextContent();
            String name = nodeName.getTextContent();
            map.put(id, name);
        }

    } catch (IOException e) {
        e.printStackTrace();
    } catch (XPathExpressionException e) {
        e.printStackTrace();
    } finally {
        file.close();
    }
    return map;
}

异常(exception):

java.io.IOException: Stream closed
    at java.io.BufferedInputStream.getBufIfOpen(BufferedInputStream.java:162)
    at java.io.BufferedInputStream.fill(BufferedInputStream.java:206)
    at java.io.BufferedInputStream.read(BufferedInputStream.java:254)

javax.xml.xpath.XPathExpressionException: java.io.IOException: Stream closed
    at org.apache.xpath.jaxp.XPathImpl.evaluate(XPathImpl.java:481)

Caused by: java.io.IOException: Stream closed
    at java.io.BufferedInputStream.getBufIfOpen(BufferedInputStream.java:162)
    at java.io.BufferedInputStream.fill(BufferedInputStream.java:206)
    at java.io.BufferedInputStream.read(BufferedInputStream.java:254)

我已经关闭了流,但它显然仍然是一个问题?

最佳答案

//将 xml-apis.jar 用于以下类,例如 DocumenttBuilderFactory。

//XPATH expressions
public static final String IdExpr = "/NameDefinition/@Id";
public static final String NameExpr = "/NameDefinition/@Name";

Map<String,String> evaluateXML(String file, String IdExpr, String NameExpr) {
    Map < String,
    String > returnMap = null;
    try {
        FileInputStream fis = new FileInputStream(new File(file));

        DocumentBuilderFactory builderFactory = DocumentBuilderFactory
            .newInstance();
        DocumentBuilder builder = builderFactory.newDocumentBuilder();
        Document xmlDocument = builder.parse(fis);

        XPath xPath = XPathFactory.newInstance().newXPath();

        String Id = xPath.compile(IdExpr).evaluate(
                xmlDocument);
        String Name = xPath.compile(NameExpr).evaluate(
                xmlDocument);

        returnMap = new HashMap < String,
        String > ();

        returnMap.put(Id, Name);
    }

关于java - 在 Java 中使用 XPath 解析 XML,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32955073/

相关文章:

java - 获取 XSD 验证错误的父元素

java - 忽略 Android 生成的文件,GIT

java - 同步代码块

java - 验证 oracle 的 java 源中的 xml 文档

java - 在 Java 中将节点 append 到 xml

java - 通过 XPath 将任意 XML 字符串插入 XML 文档的代码

php - 是否可以直接在 PHP 对象上使用 XPath?

Java:通过正则表达式字符串解析用元素丰富 xml

java - RecyclerViewAdapter OnBindViewHolder 的 ID 为空

java - log4j2 自定义 kafka Appender 插件被忽略