2

我有一个非常简单的 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 标记。我应该如何做到这一点?

4

5 回答 5

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);
}
于 2013-03-14T05:30:57.740 回答
1

除非你真的知道你在 XML 中得到了什么,否则这是非常不鼓励的

响应体:

<?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];
于 2013-03-14T05:28:44.453 回答
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));
}
于 2013-03-14T05:36:30.753 回答
0

尝试拆分如下:

String[] strTemp = strXMLOutput.split("<TagName>");
strTemp = strTemp[1].split("</TagName>");
String strValue = strTemp[0]

100% 会起作用的。

于 2013-03-14T05:40:56.170 回答
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*/

    }

}
于 2013-03-14T05:49:11.430 回答