I was writing this for a "hack" of sorts of GtkAtlantic, but rolling is done serverside, so that project ended up ending itself. Reguardless, I wrote this to parse some of it's packet data.
/**
Makes parsing XML tags easy<br />
Has methods for getting the tag's name, and properties
@author William LaFrance
@version 1.2
*/
public class XMLParse
{
/**
Gets the name of the XML tag
@param data Full XML tag
@return Tag name
*/
public static String xml_get_tagname(String data)
{
String[] split = data.split(" ");
return split[0].substring(1);
}
/**
Gets a paramater's value in an XML tag
@param data Full XML tag
@param propname Name of property to return value of
@return Value of property represented by propname
*/
public static String xml_get_property(String data, String propname)
{
String[] split = stripBeginningAndEnd(data).split(" ");
for (int i = 0; i < split.length; i++)
{
String[] split2 = split[i].split("=");
if (split2[0].equalsIgnoreCase(propname))
{
return stripQuotes(split2[1]);
}
}
return null;
}
/**
Gets the list of properties in the tag
@param data Full XML tag
@return Array of property names
*/
public static String[] xml_listprops(String data)
{
String[] split = stripBeginningAndEnd(data).split(" ");
for (int i = 0; i < split.length; i++)
{
split[i] = split[i].split("=")[0];
}
return split;
}
private static String stripQuotes(String data)
{
return data.substring(1, data.length() - 1);
}
private static String stripBeginningAndEnd(String data)
{
int a, b;
a = 2 + xml_get_tagname(data).length();
b = data.length() - 2;
return data.substring(a, b);
}
}
Tested with following code:
public class XMLParseTest
{
public static void main(String args[])
{
String data = "<r n=\"Aegwynn\" t=\"2\" s=\"2\" l=\"0\"/>";
String propList = ""; String[] propArray = XMLParse.xml_listprops (data);
for (int i = 0; i < propArray.length; i++)
{
propList = propList.concat(propArray[i]).concat("; ");
}
System.out.println("TAG NAME: " + XMLParse.xml_get_tagname (data));
System.out.println("PROPERTY LIST: " + propList);
for (int i = 0; i < propArray.length; i++)
{
System.out.println("VALUE OF '" + propArray[i] + "': " + XMLParse.xml_get_property(data, propArray[i]));
}
}
}
Command line output:
joe@deadmeat:~/Desktop/Monopd Leet Hax $ javac *.java && java XMLParseTest
TAG NAME: r
PROPERTY LIST: n; t; s; l;
VALUE OF 'n': Aegwynn
VALUE OF 't': 2
VALUE OF 's': 2
VALUE OF 'l': 0
EDIT -
Because I'm too awesome to ever do anything half-way, I've added a method to return a list of propertys in an array.
EDIT -
I was stupid (hey, who knew) and forgot to end my tag with /> instead of >. Fixed. Replaced with an actual XML tag (from
the WoW realm status page) and changed the tester to loop through all properties instead of hardcoded ones.