need a snippet ( probably with XPAth ) to traverse all XML nodes and produce an output file

Posted on 2009-05-10
Last Modified: 2013-11-11
containing all full node names ( combining all levels, i.e. level1name.level2name. etc. .. ) and
their values for example, <abc>
                                                 <val1tag> value 1 <val1tag\>

would produce abc.val1tag = value 1
Question by:AlexF777
  • 2
LVL 23

Expert Comment

ID: 24348122
Using XSL may be a better way.

Could you provide a bit more detail on what you need. A more extensive and complete example of the input and output would help.

Expert Comment

ID: 24349809
Attached is a sample java code to get the result. Not sure if this is what you are looking for -

Accepted Solution

sundar62 earned 500 total points
ID: 24349866



import javax.xml.transform.Transformer;

import javax.xml.transform.dom.DOMSource;


import org.w3c.dom.Document;

import org.w3c.dom.NamedNodeMap;

import org.w3c.dom.Node;

import org.w3c.dom.NodeList;

import java.util.ArrayList;

import java.util.*;

import javax.xml.parsers.DocumentBuilder;

import javax.xml.parsers.DocumentBuilderFactory;

import javax.xml.transform.Source;

import javax.xml.transform.dom.DOMSource;

public class XmlWalker {


    public static void main(String[] args) throws Exception {

        new XmlWalker().walk("persons.xml");



    private void walk(String filename) throws Exception {

        Document dom = parseXmlFile(filename);

        printXpath("", dom);



    private Document parseXmlFile(String filename) throws Exception {

        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();

        DocumentBuilder db = dbf.newDocumentBuilder();

        return db.parse(filename);



    private void printXpath(String xpath, Node node) {

        short type = node.getNodeType();

        if (type == Node.DOCUMENT_NODE || type == Node.ELEMENT_NODE) {

            if (type == Node.ELEMENT_NODE) {

                xpath += nodePath(node);

                System.out.println(xpath + "-->" + node.getTextContent());


            NodeList children = node.getChildNodes();

            for (int index = 0; index < children.getLength(); ++index) {

                printXpath(xpath, children.item(index));





    private String nodePath(Node node) {

        Node parent = node.getParentNode();

        StringBuilder buf = new StringBuilder(256);


        if (parent == null || parent.getNodeType() == Node.DOCUMENT_NODE) {


        } else if (getNodeId(node) != null) {

            buf.append(".").append(node.getNodeName()).append("[@id='").append(getNodeId(node) + "']");

        } else {


            List<Node> siblings = getChildrenByName(parent, node.getNodeName());

            if (siblings.size() > 1) {

                buf.append("[").append((siblings.indexOf(node) + 1)).append("]");



        return buf.toString().toString();



    private String getNodeId(Node node) {

        Node id = getNamedItem(node.getAttributes(), "id");

        return (id != null) ? id.getNodeValue() : null;



    private Node getNamedItem(NamedNodeMap attributes, String name) {

        return (attributes != null) ? attributes.getNamedItem(name) : null;



    private List<Node> getChildrenByName(Node parent, String name) {

        NodeList children = parent.getChildNodes();

        List<Node> results = new ArrayList<Node>();

        for (int i = 0; i < children.getLength(); ++i) {

            if (nameEquals(children.item(i), name))



        return results;



    private boolean nameEquals(Node child, String name) {

        return (child != null && name.equals(child.getNodeName()));



Open in new window


Featured Post

Enabling OSINT in Activity Based Intelligence

Activity based intelligence (ABI) requires access to all available sources of data. Recorded Future allows analysts to observe structured data on the open, deep, and dark web.

Join & Write a Comment

Suggested Solutions

The object model of .Net can be overwhelming at times – so overwhelming that quite trivial tasks often take hours of research. In this case, the task at hand was to populate the datagrid from SQL Server database in Visual Studio 2008 Windows applica…
Introduction In my previous article ( I showed you how the XML Source component can be used to load XML files into a SQL Server database, us…
Internet Business Fax to Email Made Easy - With eFax Corporate (, you'll receive a dedicated online fax number, which is used the same way as a typical analog fax number. You'll receive secure faxes in your email, fr…
When you create an app prototype with Adobe XD, you can insert system screens -- sharing or Control Center, for example -- with just a few clicks. This video shows you how. You can take the full course on Experts Exchange at

705 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

15 Experts available now in Live!

Get 1:1 Help Now