Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simple way to extract data from XML with Java

Tags:

java

regex

xml

What would be the simplest way to extract data from XML in Java? The XML data is always in the form:

<?xml version=\"1.0\" encoding=\"UTF-8\"?>
<groups>GROUPNAME</groups>

and all I want to do is capture the groupname in a string. I've tried using a regular expression, but I'm struggleing to write the pattern code:

String xmlline = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<groups>XWiki.G_SW_DEV</groups>";
String pattern = "";
Pattern r = Pattern.compile(pattern);
Matcher m = r.matcher(xmlline);
if(m.find()){
    ....                     
}

As described in: http://www.tutorialspoint.com/java/java_regular_expressions.htm

Any advice on the pattern code or is there a better way to extract the XML data?

like image 994
Gerrie van Wyk Avatar asked Feb 12 '26 02:02

Gerrie van Wyk


1 Answers

Classical advice: dont use regex. It seems easy at begining, but it's not so easy.

and there are many classical libraries for XML which do it well !

see this: Java:XML Parser

and then, you only need to do this to retrieve elements:

doc.getElementsByTagName("groups")

getElementsByTagName

and, something like that

doc.getElementsByTagName("method").item(0).getTextContent() 
like image 57
guillaume girod-vitouchkina Avatar answered Feb 13 '26 16:02

guillaume girod-vitouchkina