我有一个非常简单的XML:
<?xml version="1.0" encoding="utf-8"?>
<string xmlns="http://icacec.com/">TRUE,Hrithik Sharma,201301-11</string>
现在,我想在 3个单独的变量中仅提取 TRUE , Hrithik Sharma , 201301-11 。
我可以根据“,”这样分割字符串:
String[] parts = responseBody.split(",");
String response_auth = parts[0];
String user_name = parts[1];
String user_number=parts[2];
但我面临的问题是,字符串不是独立提取的。更确切地说,没有XML标签。我该怎么做?
答案 0 :(得分:3)
这可以解决这个简单的情况,但是没有解析你将如何处理其他条件?
public static void main(String[] args) {
String raw = "<string xmlns=\"http://icacec.com/\">TRUE,Hrithik Sharma,201301-11</string>";
raw = raw.substring(0, raw.lastIndexOf("<"));
raw = raw.substring(raw.lastIndexOf(">") + 1, raw.length());
String [] contents = raw.split(",");
for (String txt : contents)
System.out.println(txt);
}
答案 1 :(得分:1)
除非您真正了解XML中的内容,否则不鼓励这样做
responseBody:
<?xml version="1.0" encoding="utf-8"?>
<string xmlns="http://icacec.com/">TRUE,Hrithik Sharma,201301-11</string>
代码:
String[] parts = responseBody.split(">");
String tagsFirst= parts[0];
String usefull = parts[2];
String[] actualBody = usefull.split("<");
String content = actualBody[0];
String[] contentParts=content.split(",");
//now you can have the three parts:
String truefalse=contentParts[0];
String name=contentParts[1];
String date=contentParts[2];
答案 2 :(得分:0)
试试这个正则表达式 -
"<string xmlns=\"http://icacec.com/\">(.+),(.+),(.+)</string>"
捕获组1,2和3将包含您的三个项目,即:
Pattern pattern = Pattern.compile("<string xmlns=\"http://icacec.com/\">(.+),(.+),(.+)</string>");
Matcher matcher = pattern.matcher("<string xmlns=\"http://icacec.com/\">TRUE,Hrithik Sharma,201301-11</string>");
if(matcher.matches())
{
System.out.println("Bool: " + matcher.group(1));
System.out.println("Name: " + matcher.group(2));
System.out.println("Date: " + matcher.group(3));
}
答案 3 :(得分:0)
尝试拆分:
String[] strTemp = strXMLOutput.split("<TagName>");
strTemp = strTemp[1].split("</TagName>");
String strValue = strTemp[0]
100%它会起作用。
答案 4 :(得分:0)
你可以试试这个:
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Test {
public static void main(String[] args) {
String responseBody = null;
String inputString = "<?xml version=\"1.0\" encoding=\"utf-8\"?><string xmlns=\"http://icacec.com/\">TRUE,Hrithik Sharma,201301-11</string>";
String regex = "<string[^>]*>(.+?)</string\\s*>";
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(inputString);
while(matcher.find()) {
responseBody = matcher.group(1);
System.out.println(responseBody);
}
String[] splits = responseBody.split(",");
System.out.println(splits[0]);/*prints TRUE*/
System.out.println(splits[1]);/*prints Hrithik Sharma*/
System.out.println(splits[2]);/*201301-11*/
}
}