1

Trying to get the text from "value" attribute. How do I do that using Java DOM? I will later have to go through thousands of *.xml files, that are 20 times this big and look for "failing_message" and then need to get its failing_message, that is in "value" attribute.

<?xml version="1.0" encoding="UTF-8"?>
<root version="14" libraryDocVersion="17">
  <node type="flow" id="3224122a-b164-422c-add2-974f22229b6a">
    <child name="inputs">
      <collection type="list">
        <node type="staticBinding" id="3333333-9dd4-4363-9f15-1333c433335">
                <attribute name="annotation"></attribute>
                <attribute name="assignFromContext">false</attribute>
                <attribute name="assignToContext">false</attribute>
                <attribute name="inputSymbol">failing_message</attribute>
                <attribute name="inputType">String</attribute>
                <attribute name="isList">false</attribute>
                <attribute name="isPersisted">true</attribute>
                <attribute name="last_modified_by">admin</attribute>
                <attribute name="listDelimiter">,</attribute>
                <attribute name="modifiedTimestamp">1428938670220</attribute>
                <attribute name="record">false</attribute>
                <attribute name="required">true</attribute>
                <attribute name="uuid">3333333-30c4-3333-3333-333800d10333</attribute>
                <attribute name="value">Could not get free IP address for installation</attribute>
         </node>
       </collection>
    </child>
  </node>
</root>
1

2 Answers 2

1

You should use xpath to search XML documents. it is the most efficient way to search a loaded XML doc.

Here is the piece of code to get you the text value of an attribute element with a name="value" attribute

import javax.xml.parsers.*;
import javax.xml.xpath.*;
import org.w3c.dom.*;

public static void main(String[] args)
{
    try {
            Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse("C://Temp/xx.xml");

            XPath xPath =  XPathFactory.newInstance().newXPath();
            Node n = (Node)xPath.compile("//attribute[@name='value']")
                    .evaluate(doc, XPathConstants.NODE);
            System.out.println(n.getTextContent());
    } catch (Exception e) {
        e.printStackTrace();
    }
}

Output

Could not get free IP address for installation
Sign up to request clarification or add additional context in comments.

3 Comments

Awesome, cheers! Only problem is, that the XML is much bigger and there are multiple <attribute name="value"> so you somehow have to link it to the failing_message
have a look into xpath syntax. it is very feature rich with wildcards and capturing groups
I looked at it, but I think XPath is too weak for my purpose. :(
0

for you simple usecase you can use sax, because it is faster:

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

import javax.xml.parsers.SAXParserFactory;

public class ValueHandler extends DefaultHandler{

    private boolean valueAttributeElement;
    private StringBuilder content = new StringBuilder();
    private String answer;

    @Override
    public void startElement(String uri, String localName, String qname, Attributes attributes) throws SAXException{
        valueAttributeElement = localName.equals("attribute") && "value".equals(attributes.getValue("name"));
        content.setLength(0);
    }

    @Override
    public void characters(char[] chars, int start, int length) throws SAXException{
        if(valueAttributeElement)
            content.append(chars, start, length);
    }

    @Override
    public void endElement(String uri, String localName, String qname) throws SAXException{
        if(valueAttributeElement)
            answer = content.toString();
    }

    public String getAnswer(){
        return answer;
    }

    public static void main(String[] args) throws Exception{
        String file = "/Users/santhosh/tmp/jlibs-test/src/main/resources/test.xml";
        SAXParserFactory factory = SAXParserFactory.newInstance();
        factory.setNamespaceAware(true);
        ValueHandler valueHandler = new ValueHandler();
        factory.newSAXParser().parse(file, valueHandler);
        System.out.println("answer: "+valueHandler.getAnswer());
    }
}

output is:

answer: Could not get free IP address for installation

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.