| Author |
Reading a simple XML File
|
Pete Dawn
Greenhorn
Joined: Sep 28, 2006
Posts: 17
|
|
guys, i have a xml file with this format, <a> <b name="test0" value="0"> <d> <c name="test1"/> <c name="test2"/> <g> <e name="test3" value="1"/> <f name="test4" value="2"/> </g> </d> </b> </a> basically i have a file which is multiple levels deep and has corresponding element attributes. can somebody please help me out to read the individual attributes from each line. i am new to XML in java and am having a tough time with it. thanks.
|
 |
Henry Wong
author
Sheriff
Joined: Sep 28, 2004
Posts: 16695
|
|
There are multiple ways to do this... the two most well known APIs are SAX and DOM. SAX uses an event based API to parse an XML document. And DOM just parses the document, returning an object tree that represents the XML document. If you have Java 1.4 or higher, these parsers are built-in. Nothing to install, just google SAX2 or DOM2 for more information. If you have Java 6, you have one more option -- JAXB. JAXB is similar to DOM but it provides Java bindings. This means instead of traversing a DOM tree by generic elements names, you actually traverse it by calling methods with the name of the XML fields. Henry
|
Books: Java Threads, 3rd Edition, Jini in a Nutshell, and Java Gems (contributor)
|
 |
Pete Dawn
Greenhorn
Joined: Sep 28, 2006
Posts: 17
|
|
have got this so far, but its only reading b name="test0" and not its child nodes. i basically want to parse the entire file and obtain individual element attributes. DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder(); Document doc = docBuilder.parse (new File("settings.xml")); doc.getDocumentElement ().normalize (); Node n; NodeList nodes = doc.getDocumentElement().getChildNodes(); for( int i=0 ; i<nodes.getLength(); i++ ) { n = nodes.item( i ); if( n.getNodeType() == Node.ELEMENT_NODE ) { if( n.getNodeName().equals( "b" ) ) { NamedNodeMap attrs = n.getAttributes(); String x = attrs.getNamedItem("name").getNodeValue(); String y = attrs.getNamedItem("value").getNodeValue(); } } else { } }>
|
 |
Paul Clapham
Bartender
Joined: Oct 14, 2005
Posts: 16483
|
|
|
That's because the document element only has the one <b> child element. If you want to look at all the elements in the document, one way is to write code that recursively scans all the child nodes, and their children, and so on.
|
 |
Pete Dawn
Greenhorn
Joined: Sep 28, 2006
Posts: 17
|
|
|
Yes i think thats the kinda things i am after. can you provide some sample code. thanks.
|
 |
 |
|
|
subject: Reading a simple XML File
|
|
|