|
-
Aug 7th, 2007, 10:33 AM
#1
Thread Starter
Member
Print XML tag
Hey,
I have written some java code to Parse an XML file.
It is almost exactly the same as the code here:
http://www.developertutorials.com/print/393.html
Basically, I have it returning the XML values but what I want to be able to do now is to return the tag itself.
So if we have:
<age>22</age>
I have the code which will return: 22
Now I need the code to show the actual TAG: <age>
Does anyone know how this can be done????
THANKS!!!!!!
-
Aug 7th, 2007, 12:42 PM
#2
Re: Print XML tag
the
Code:
doc.getDocumentElement()
Gets the first element in the document.
The
Code:
doc.getChildNodes()
Loads child nodes following the first node.
It's a NodeList object, so you can iterate your way in it
"I'm not normally a praying man, but if you're up there, save me... Superman!" - Homer Simpson
My Blog
-
Aug 8th, 2007, 05:00 AM
#3
Thread Starter
Member
Re: Print XML tag
Cheers for the reply ComputerJy
It's a NodeList object, so you can iterate your way in it
Can you please give an example?
-
Aug 8th, 2007, 12:42 PM
#4
Re: Print XML tag
Code:
import java.io.File;
import java.io.IOException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
public class ReadAndPrintXMLFile {
public static void main(String argv[]) throws ParserConfigurationException,
SAXException, IOException {
DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory
.newInstance();
DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
Document doc = docBuilder.parse(new File("book.xml"));
// normalize text representation
doc.getDocumentElement().normalize();
System.out.println("Root element of the doc is "
+ doc.getDocumentElement().getNodeName());
System.out.println("******" + doc.getDocumentElement().getNodeName());
printNodesList(doc.getDocumentElement());
}// end of main
private static void printNodesList(Node node) {
if (node.hasChildNodes()) {
NodeList children = node.getChildNodes();
for (int i = 0; i < children.getLength(); i++) {
System.out.println(children.item(i));
if (children.item(i).hasChildNodes()) {
printNodesList(children.item(i));
}
}
}
}
}
"I'm not normally a praying man, but if you're up there, save me... Superman!" - Homer Simpson
My Blog
-
Aug 17th, 2007, 02:55 AM
#5
Thread Starter
Member
Re: Print XML tag
Cheers mate
Once I knew that what I was looking for is called an XML 'Attribute'
I worked it out and used this:
Code:
String maturity = fstElmnt.getAttribute("xc:value");
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|