1

I'd like to parse this XML file:

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

To get the values for ID and Name nodes. The data structure I'd like returned is Map(String,String) so ID is key and Name is value.

How can I accomplish this in Java 6?

Edit:

Here's my current implementation, however

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

Exceptions:

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)

I've closed the stream but it's apparently still a problem?

2
  • 1
    Is it mandatory for you to use x-path? If not, then you can do the parsing using DOM objects. stackoverflow.com/questions/26556878/parse-xml-using-dom-java might help you. Commented Oct 5, 2015 at 18:37
  • I'd like to use Xpath, it's not required Commented Oct 5, 2015 at 19:01

2 Answers 2

1

// Use xml-apis.jar for the below classes like 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);
    }
Sign up to request clarification or add additional context in comments.

2 Comments

Use the above approach...It will be pretty straightforward.
Nice simplicity but for some reason this implementation does not work
0

The solution was straught forward, I should have done some research before posting this question:

static Map<String,String> parseDoc(String pathToFriendlyNamesFile) 
        throws ParserConfigurationException, 
        SAXException, 
        IOException {

    File f = new File(pathToFriendlyNamesFile); 
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    DocumentBuilder db = dbf.newDocumentBuilder();
    Document doc = db.parse(f);

    Map<String,String> map = new LinkedHashMap<String, String>();

    doc.getDocumentElement().normalize();

    System.out.println("Root Element: "+doc.getDocumentElement().getNodeName());

    NodeList nList = doc.getElementsByTagName("NameDefinition");
    System.out.println("How many nodes? "+nList.getLength());
    for(int i=0;i<nList.getLength();i++) {
        Node nNode = nList.item(i);

        if(nNode.getNodeType() == Node.ELEMENT_NODE) {
            Element eElement = (Element) nNode;
            String nodeID = eElement.getElementsByTagName("ID").item(0).getTextContent();
            String name = eElement.getElementsByTagName("Name").item(0).getTextContent();

            System.out.println("ID: "+nodeID+" Name: "+name);
            map.put(nodeID, name);
        }
    }

    return map;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.