Want to win a PS4? Go Premium and enter to win our High-Tech Treats giveaway. Enter to Win

x
?
Solved

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

Posted on 2009-05-10
3
Medium Priority
?
259 Views
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
0
Comment
Question by:AlexF777
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 2
3 Comments
 
LVL 23

Expert Comment

by:Tony McCreath
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.
0
 
LVL 1

Expert Comment

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

Accepted Solution

by:
sundar62 earned 2000 total points
ID: 24349866

import java.io.OutputStream;
import java.io.PrintStream;
 
import javax.xml.transform.Transformer;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
 
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) {
            buf.append("/").append(node.getNodeName());
        } else if (getNodeId(node) != null) {
            buf.append(".").append(node.getNodeName()).append("[@id='").append(getNodeId(node) + "']");
        } else {
            buf.append('.').append(node.getNodeName());
            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))
                results.add(children.item(i));
        }
        return results;
    }
 
    private boolean nameEquals(Node child, String name) {
        return (child != null && name.equals(child.getNodeName()));
    }
} 

Open in new window

0

Featured Post

Free learning courses: Active Directory Deep Dive

Get a firm grasp on your IT environment when you learn Active Directory best practices with Veeam! Watch all, or choose any amount, of this three-part webinar series to improve your skills. From the basics to virtualization and backup, we got you covered.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Welcome my friends to the second instalment and follow-up to our Minify and Concatenate Your Scripts and Stylesheets (http://www.experts-exchange.com/Programming/Languages/.NET/ASP.NET/A_4334-Minify-and-Concatenate-Your-Scripts-and-Stylesheets.html)…
This article shows how to deploy dynamic backgrounds to computers depending on the aspect ratio of display
This tutorial will teach you the special effect of super speed similar to the fictional character Wally West aka "The Flash" After Shake : http://www.videocopilot.net/presets/after_shake/ All lightning effects with instructions : http://www.mediaf…
Are you ready to place your question in front of subject-matter experts for more timely responses? With the release of Priority Question, Premium Members, Team Accounts and Qualified Experts can now identify the emergent level of their issue, signal…

618 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