Created
November 13, 2012 06:48
-
-
Save samiron/4064365 to your computer and use it in GitHub Desktop.
XML Parsing Examples with XOM
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?xml version="1.0"?> | |
<students> | |
<student href="http://first.com"> | |
<name rel="first">Sriram</name> | |
<age>2</age> | |
</student> | |
<student href="http://second.com"> | |
<name rel="second">Venkat</name> | |
<age>29</age> | |
</student> | |
<student href="http://third.com"> | |
<name rel="third">Anu</name> | |
<age>28</age> | |
</student> | |
</students> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package test.xml; | |
import java.io.IOException; | |
import java.io.InputStream; | |
import nu.xom.Nodes; | |
import nu.xom.Builder; | |
import nu.xom.Document; | |
import nu.xom.Element; | |
import nu.xom.Elements; | |
import nu.xom.ParsingException; | |
import nu.xom.ValidityException; | |
public class XomParsing { | |
/** | |
* @param args | |
*/ | |
public static void main(String[] args) throws ValidityException, ParsingException, IOException { | |
XomParsing p = new XomParsing(); | |
Builder builder = new Builder(); | |
InputStream ins = XomParsing.class.getClassLoader().getResourceAsStream("student_input.xml"); | |
Document doc = builder.build(ins); | |
// p.traverse(doc); | |
p.applyXpath(doc); | |
} | |
public void traverse(Document doc) { | |
Element root = doc.getRootElement(); | |
System.out.println("Root Node : " + root.getLocalName()); | |
// Get children | |
Elements students = root.getChildElements(); | |
Element nameChild = null; | |
for (int i = 0; i < students.size(); i++) { | |
System.out.println(" Child : " + students.get(i).getLocalName()); | |
// Get first child with tag name as 'name' | |
nameChild = students.get(i).getFirstChildElement("name"); | |
if (nameChild != null) { | |
System.out.println(" Name : " + nameChild.getValue()); | |
} | |
} | |
} | |
private void applyXpath(Document doc) { | |
Element root = doc.getRootElement(); | |
Nodes result = root.query("/students/student[name[@rel=\"second\"]]/@href"); | |
System.out.println(result.get(0).getValue()); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment