Apr
16
Took me half a day to figure out matcher.find() had to be called first. Gaah!
RegexTest.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
| import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Tester {
public static void main(String args[])
{
Pattern pattern = Pattern.compile("name=\"QTime\">(\\d+)</int>");
Matcher matcher = pattern.matcher("<response><lst name=\"responseHeader\">" +
"<int name=\"status\">0</int><int name=\"QTime\">2</int></lst></response>");
try {
if(matcher.find()) {
System.out.println(matcher.group(1));
}
}
catch (Exception e) {
System.out.println("Couldn't find QTime");
}
}
} |
P.S. I love Python
Mar
29
Of late, I have been working with Java. And one of the issues that I faced was XML parsing. With so many libraries available, I decided to stick to jaxp. What follows is sample code to Tree walk over the nodes:
TreeWalk.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
| import java.io.File;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
public class Tester {
public static void main(String args[])
{
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setNamespaceAware(false);
try {
DocumentBuilder builder = factory.newDocumentBuilder();
org.w3c.dom.Document doc = builder.parse(new File(args[0]));
NodeList nodes1 = doc.getChildNodes();
for(int i=0; i<nodes1.getLength(); i++) {
TreeWalk(nodes1.item(i), 0);
}
}
catch(Exception e) {
e.printStackTrace();
}
}
private static void TreeWalk(Node n, int level)
{
if(n.getNodeType() != Node.TEXT_NODE) {
for(int i=0; i<level; i++)
System.out.print(" ");
System.out.print(n.getNodeName() + ":");
}
else {
System.out.println(n.getNodeValue().trim());
}
NodeList list = n.getChildNodes();
for(int i=0; i<list.getLength(); i++) {
TreeWalk(list.item(i), level+1);
}
}
} |