4

Here is my xml code...

<flow>
    <TaskID>100</TaskID>
    <TaskID>101</TaskID>
    <TaskID>102</TaskID>
    <TaskID>103</TaskID>    
</flow>

I want to know how to get taskID values in a for loop in java. Please help me...

4
  • are you using an xml to java binding library, for example JAXB to work with xml from java? Commented Nov 13, 2012 at 6:44
  • 1
    +1. For not trying to use regex. Commented Nov 13, 2012 at 6:45
  • 1
    What have you tried? Is the XML particularly large? Are you able to use 3rd party libraries such as jdom? Commented Nov 13, 2012 at 6:48
  • I am using javax.xml.parsers to parse the xml file. And org.w3c.dom to access the tags Commented Nov 14, 2012 at 4:39

6 Answers 6

9

DOM parser solution, fairly simple, no extra libraries required.

public static void main(String[] args) throws SAXException, IOException,
        ParserConfigurationException {

    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = factory.newDocumentBuilder();

    String input = "<outer>";
    input += "<otherstuff><TaskID>123</TaskID></otherstuff>";
    input += "<flow>";
    input += "<TaskID>100</TaskID>";
    input += "<TaskID>101</TaskID>";
    input += "<TaskID>102</TaskID>";
    input += "<TaskID>103</TaskID>";
    input += "</flow>";
    input += "</outer>";
    Document document = builder.parse(new InputSource(new StringReader(
            input)));

    NodeList flowList = document.getElementsByTagName("flow");
    for (int i = 0; i < flowList.getLength(); i++) {
        NodeList childList = flowList.item(i).getChildNodes();
        for (int j = 0; j < childList.getLength(); j++) {
            Node childNode = childList.item(j);
            if ("TaskID".equals(childNode.getNodeName())) {
                System.out.println(childList.item(j).getTextContent()
                        .trim());
            }
        }
    }
}

You'd need to use a FileReader instead if your input came from a file.

Document document = builder.parse(new InputSource(new FileReader(
        new File("foo.xml"))));

An alternative to getElementsByTagName() is XPath, a query language for XML, this is particularly useful if you have complicated set of conditions to match.

XPathFactory xPathfactory = XPathFactory.newInstance();
XPath xpath = xPathfactory.newXPath();
XPathExpression expr = xpath.compile("//flow/TaskID/text()");

Object result = expr.evaluate(document, XPathConstants.NODESET);
NodeList nodes = (NodeList) result;
for (int i = 0; i < nodes.getLength(); i++) {
    System.out.println(nodes.item(i).getTextContent());
}

If your XML file is large, like 100s of MB / GB or you're on a low memory platform then consider a SAX parser.

String input = "<flow><TaskID>100</TaskID><TaskID>101</TaskID><TaskID>102</TaskID><TaskID>103</TaskID></flow>";
SAXParser sax = SAXParserFactory.newInstance().newSAXParser();
DefaultHandler handler = new DefaultHandler() {
    private StringBuilder buffer = new StringBuilder();
    @Override
    public void endElement(String uri, String localName, String qName)
            throws SAXException {
        if ("TaskID".equals(qName)) {
            System.out.println(buffer);
            buffer = new StringBuilder();
        }
    }
    @Override
    public void characters(char[] ch, int start, int length)
            throws SAXException {
        buffer.append(ch, start, length);
    }
    @Override
    public void startElement(String uri, String localName,
            String qName, Attributes attributes) throws SAXException {
        buffer = new StringBuilder();
    }
};
sax.parse(new InputSource(new StringReader(input)), handler);
Sign up to request clarification or add additional context in comments.

3 Comments

I am using DOM parser to parse the input file. By using getChildNodes() method of <flow> tag i am getting all child tags. but this method is taking space and next line characters also as tags and giving to me. And I can't use document.getElementsByTagName("TaskID"), because in my xml file <TaskID> tag is present in under some other tags also. And I can't change the tag name. so please tell me how to get only tag values..
@user1820087 I've updated my solution to have a more complex input to represent your problem. I'd recommend using XPath for this type of problem because the expression is simply "//flow/TaskID/text()" without the need for looping over getChildNodes() etc.
why use the NODESET XPathConstant?
3

Here's an example using JDOM, which provides a more pleasant API over existing Java XML parsers:

import java.io.File;
import org.jdom2.*;
import org.jdom2.input.*;

public class Test {
    // TODO: More appropriate exception handling :)
    public static void main (String[] args) throws Exception {
        SAXBuilder builder = new SAXBuilder();
        Document doc = builder.build(new File("test.xml"));
        Element root = doc.getRootElement();
        for (Element element : root.getChildren("TaskID")) {
            System.out.println(element.getText());
        }
    }
}

Of course, this assumes that the XML document is small enough to be loaded into memory.

(Obviously you can use the built-in libraries too, and if you're not doing much XML work then that would be fine - I just find them a bit primitive if you're doing any significant amount of work.)

Comments

0

With xpath Here is more information:

http://www.vogella.com/articles/JavaXML/article.html

Comments

0

I personally use JDOM library for all my XML manipulation.. Below is how I would do it;

 String xml = "<flow> " +
                   "<TaskID>100</TaskID>" +
                   "<TaskID>101</TaskID>" +
                   "<TaskID>102</TaskID>" + 
                   "<TaskID>103</TaskID>" + 
              "</flow>";

org.jdom.Document doc = new SAXBuilder().build(new StringReader(xml));

org.jdom.Element rootElement = doc.getRootElement();

List<Element> eles = rootElement.getChildren("TaskID");

for(Element el : eles)
   System.out.println(el.getName()+" : "+el.getValue());

You can get it's documentation here: http://www.jdom.org/

Comments

0

Read Xml Children with SAX

<?xml version="1.0"?> 
<Patriarch>
   <name>Bill</name>
   <wife>
      <name>Vi</name>
   </wife>
   <son>
      <name>Bill</name>
   </son>
   <daughter>
      <name>Jeri</name>
      <husband>
         <name>Mark</name>
      </husband>
      <son>
         <name>Greg</name>
      </son>
      <son>
         <name>Tim</name>
      </son>
      <son>
         <name>Mark</name>
      </son>
      <son>
         <name>Josh</name>
         <wife>
            <name>Kristine</name>
         </wife>
         <son>
            <name>Blake</name>
         </son>
         <daughter>
            <name>Liah</name>
         </daughter>
      </son>
   </daughter>
</Patriarch>

And Java code:

public class ParseXmlSAX {

    public static void main(String[] args) {
        new ParseXmlSAX("file.xml");
    }

    public ParseXmlSAX(final String file) {
        try {

            SAXParserFactory factory = SAXParserFactory.newInstance();
            SAXParser saxParser = factory.newSAXParser();

            DefaultHandler handler = new DefaultHandler() {
                String key = null;

                public void startElement(String uri, String localName, String qName, Attributes attributes)
                        throws SAXException {

                    if (key == null)
                        key = "|";
                    else
                        key += qName + "|";

                }

                public void endElement(String uri, String localName, String qName) throws SAXException {

                    if (!key.equals("|"))
                        key = key.substring(0, key.lastIndexOf(qName));

                }

                public void characters(char ch[], int start, int length) throws SAXException {
                    String conteudo = new String(ch, start, length).trim();

                    if (!conteudo.isEmpty()) {
                        System.out.println(key + " = " + conteudo);
                    }

                }

            };

            saxParser.parse(this.getClass().getResourceAsStream(file), handler);

        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}

Comments

-1
public class Modifier {

    public void modifyXML() {
        String strSrcFile = "E:\\projects\\input\\sample.xml";
        String strOutputFile = "E:\\projects\\output\\sample.xml";
        try {
            DocumentBuilderFactory docFactory = DocumentBuilderFactory
                    .newInstance();
            DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
            Document doc = docBuilder.parse(strSrcFile);
            Node company = doc.getFirstChild();
            System.out.println(company.hasChildNodes());
            NodeList nl = company.getChildNodes();
            for (int i = 0; i < nl.getLength(); i++) {
                Node node = nl.item(i);
                // System.out.println("inner node::"+node.getNodeName());

                if (node.hasChildNodes()) {
                    System.out.println("outer node::" + node.getNodeName());
                    readChildNodes(node);
                } else {

                }
            }

            TransformerFactory transformerFactory = TransformerFactory
                    .newInstance();
            Transformer transformer = transformerFactory.newTransformer();
            DOMSource source = new DOMSource(doc);
            StreamResult result = new StreamResult(new File(strOutputFile));
            transformer.transform(source, result);

        } catch (Exception ee) {
            ee.printStackTrace();
        }
        // Get the root element

    }

    public void readChildNodes(Node node)
    {

        NodeList nl = node.getChildNodes();


        for (int i = 0; i < nl.getLength(); i++) {
            Node innernode = nl.item(i);
            //System.out.println("mediam stage  node::"+innernode.getNodeName());
            if (innernode.hasChildNodes()) {
                System.out.println("inner node::"+innernode.getNodeName());

                readChildNodes(innernode);
            }
            else{

                System.out.println("node dont have childs node::"+innernode.getNodeName());
            }

        }
    }

    public void replaceGraphicCode(Node innernode) {
        NamedNodeMap attr = innernode.getAttributes();
        Node nodeAttr = attr.getNamedItem("id");
        String IDvalue = nodeAttr.getTextContent();


        // nodeAttr.setTextContent("2");
    }

    public void replaceOriginator(Node innernode) {
        NamedNodeMap attr = innernode.getAttributes();
        Node nodeAttr = attr.getNamedItem("enterpriseCode");


    }

    public static void main(String[] args) {
        Modifier objModifier = new Modifier();
        objModifier.modifyXML();
    }
}

1 Comment

Welcome to Stackoverflow. Could you please describe your code and how your answer adds value to this question that hasn't been provided by the accepted answer already? Also, why are you transforming data and accessing attributes like "enterpriseCode" that do not exist in OPs example? This looks like some generic example code for XML handling and not like an answer to the question.

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.