• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 229
  • Last Modified:

Using an XML document

Hi,

I have some code that builds an XML document object, looks like:

    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    factory.setValidating(validating);

    // Create the builder and parse the file
    Document doc = factory.newDocumentBuilder().parse(new File(filename));
    return doc;


It works fine. I made a dummy XML document that looks like:

    <xml>
        <a>a
            <a0>a0</a0>
            <a1>a1</a1>
            <a2>a2</a2>
        </a>
        <b>b
            <b0>b0</b0>
            <b1>b1</b1>
        </b>
    </xml>

Now how do I traverse the nodes of the document using the created 'doc' object? I want to be able to hit all the nodes in the document. Something like:

       System.out.println("Here's a node value: " + doc.xml.a.a1);

Thanks
0
DJ_AM_Juicebox
Asked:
DJ_AM_Juicebox
1 Solution
 
arunyeshi2000Commented:
You can do something like this..

printNodes(doc.getElementsByTagName("xml"));

//Recursive function
printNodes(NodeList nodelist){
    //Get the root Node
    NodeList nodelist = doc.getElementsByTagName(nodelist.item(0));
 
    //Loop thru and print the node values.
    for(int i=o;i<nodelist.getLength();i++){
    System.out.println(nodelist.item(i));
    printNodes(nodelist)
}

0
 
ysnkyCommented:
0
Never miss a deadline with monday.com

The revolutionary project management tool is here!   Plan visually with a single glance and make sure your projects get done.

 
DJ_AM_JuiceboxAuthor Commented:
Hi,

The only thing I don't get is how to get the text value and only the text value of the node. For example I have:

    <weight>50</weight>

and am eventually using the code:

    Node childNode = list.item(i);
    System.out.println(childNode);

how do I extract only the text element of it?

thanks
0
 
objectsCommented:
Once you have your text node use:

    Text textNode = (Text) node;
    String text = textNode.getData();
0
 
DJ_AM_JuiceboxAuthor Commented:
ok but if the particular node doesn't have text associated with it, how can I check that (right now I'm getting an exception). I need something like:

if (node.HasText()) {
    // do stuff you listed
}

Thanks
0
 
objectsCommented:
if (node instanceof TextNode)
{
0
 
DJ_AM_JuiceboxAuthor Commented:
where is TextNode defined, what do I need to import to use it? Compiler saying it's undefined,

Thanks
0
 
objectsCommented:
sorry, typo should have been:

if (node instanceof Text)
{
0
 
DJ_AM_JuiceboxAuthor Commented:
thanks
0

Featured Post

Receive 1:1 tech help

Solve your biggest tech problems alongside global tech experts with 1:1 help.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now