/** An XML file is a text file made up of tokens. A token is either a word or it is a tag.
* 1. An token is a tag if and only if it is bounded by angle brackets, e.g., .
* 2. If the second character is a forward slash (e.g., ), this a closing tag.
* 3. If the second to last character is a forward slash (e.g.,
), this is a self-closing tag.
* 4. If a tag is neither of the above, it is an opening tag.
* 5. Except for the slashes mentioned above,
* the only characters that may appear between the brackets are letters, numerals, and hyphens.
* This means, for example, that the string <> is neither a tag nor a word. It should not appear in an XML file.*/
public class XMLToken {
private String m_token;
XMLToken(String p_token) {
//token = this.token;//这句写反了,原来的写法会发生NullPointerException this.m_token = p_token; //最好区分一下是成员变量还是参数,否则很容易引入Bug } //constructor
public static void main(String[] args) {
String testArray[] = {null, "", " ", " ", "\t",
"<?xml version='1.0' encoding='ISO-8859-1' ?>", //<?xml version='1.0' encoding='ISO-8859-1' ?> ""log4j.dtd\">", // "", // "",
"",
"", // "", // "< Tag/>", //< Tag/> };
for (String testString : testArray) {
printTestResult(testString);
}
}
public static void printTestResult(String testString) {
String printString = testString;
if (printString == null) {
printString = "null"; //如果参数为null则在输出结果显示为文字列"null" } else if (printString.trim().equals("")) {
printString = "\"" + printString + "\""; //如果参数为空格则在输出结果显示为用双引号包围的空格文字列 }
//System.out.println("======" + printString + " Test Start"); try {
XMLToken xmlToken = new XMLToken(testString);
if (xmlToken.isOpeningTag()) {
System.out.println(printString + ".isOpeningTag:" + xmlToken.isOpeningTag());
}
if (xmlToken.isClosingTag()) {
System.out.println(printString + ".isClosingTag:" + xmlToken.isClosingTag());
}
if (xmlToken.isSelfClosingTag()) {
System.out.println(printString + ".isSelfClosingTag:" + xmlToken.isSelfClosingTag());
}
if (xmlToken.isTag()) {
System.out.println(printString + ".isTag:" + xmlToken.isTag());
}
if (xmlToken.isMalFormedTokens()) {
System.out.println(printString + ".isMalFormedTokens:" + xmlToken.isMalFormedTokens());
}
if (xmlToken.isWord()) {
System.out.println(printString + ".isWord:" + xmlToken.isWord());
}
} catch (Exception e) {
System.out.println(printString + ":" + e);
//e.printStackTrace();//要想看异常的详细信息,可以考虑把注释打开 }
//System.out.println("======" + printString + " Test End"); }
public boolean isOpeningTag() {
return m_token.matches("");
}
public boolean isClosingTag() {
return m_token.matches("\\w+>");
}
public boolean isSelfClosingTag() {
return m_token.matches("");
}
public boolean isTag() {
return m_token.matches("") || m_token.matches("\\w+>") || m_token.matches("");
}
public boolean isMalFormedTokens() {
return m_token.matches("") || m_token.matches("^\\w+>") || m_token.matches("");
}
public boolean isWord() {
return !isTag() && !isMalFormedTokens();
}
}