1

我正在尝试解析以下行,myline in Java 并且它不断抛出空值。

这是我尝试获取“000000010”的方法。

myline = "<status> <id>000000010</id> <created_at>2012/03/11</created_at> <text>@joerogan Played as Joe Savage Rogan in Undisputed3 Career mode, won Pride GP, got UFC title shot against Shields, lost 3 times, and retired</text> <retweet_count>0</retweet_count> <user> <name>Siggi Eggertsson</name> <location>Berlin, Germany</location> <description></description> <url>http://www.siggieggertsson.com</url> </user></status>"
p = Pattern.compile("(?i)<id.*?>(.+?)</id>", Pattern.DOTALL);
m = regex.matcher(myline);
id =m.group(1);

有什么建议吗?

4

4 回答 4

3

强烈建议使用 XML 解析器。Java中内置了一个,这是您问题的示例解决方案。为简单起见省略了异常处理程序。

DocumentBuilderFactory factory = DocumentBuilderFactory
        .newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
String input = "<status> <id>000000010</id> <created_at>2012/03/11</created_at> <text>@joerogan Played as Joe Savage Rogan in Undisputed3 Career mode, won Pride GP, got UFC title shot against Shields, lost 3 times, and retired</text> <retweet_count>0</retweet_count> <user> <name>Siggi Eggertsson</name> <location>Berlin, Germany</location> <description></description> <url>http://www.siggieggertsson.com</url> </user></status>";
Document document = builder.parse(new InputSource(new StringReader(
        input)));
String value = document.getElementsByTagName("id").item(0)
        .getTextContent();
System.out.println(value);
于 2012-03-23T22:44:44.843 回答
2

首先,您不应该使用正则表达式来解析 XML。

但除此之外,您没有正确使用正则表达式。实例化一个对象是不够的matcher,你还需要告诉它做一些事情:

if (m.find())
{
    id = m.group(1);
}
于 2012-03-23T22:18:30.980 回答
0

该网站可能会为您提供一些有关使用 Java 解析 XML 的信息 - http://www.java-samples.com/showtutorial.php?tutorialid=152

于 2012-03-23T22:19:06.080 回答
0

这行得通

String myline = "<status> <id>000000010</id> <created_at>2012/03/11</created_at> <text>@joerogan Played as Joe Savage Rogan in Undisputed3 Career mode, won Pride GP, got UFC title shot against Shields, lost 3 times, and retired</text> <retweet_count>0</retweet_count> <user> <name>Siggi Eggertsson</name> <location>Berlin, Germany</location> <description></description> <url>http://www.siggieggertsson.com</url> </user></status>";
Pattern p = Pattern.compile(".*<id>(.+)</id>.*");
Matcher m = p.matcher(myline);
if (m.matches()) {
    String id = m.group(1);
    System.out.println(id);
}

[编辑:]这也有效,而且更好:

String myline = "<status> <id>000000010</id> <created_at>2012/03/11</created_at> <text>@joerogan Played as Joe Savage Rogan in Undisputed3 Career mode, won Pride GP, got UFC title shot against Shields, lost 3 times, and retired</text> <retweet_count>0</retweet_count> <user> <name>Siggi Eggertsson</name> <location>Berlin, Germany</location> <description></description> <url>http://www.siggieggertsson.com</url> </user></status>";
Pattern p = Pattern.compile("<id>(.+)</id>");
Matcher m = p.matcher(myline);
if (m.find()) {
    String id = m.group(1);
    System.out.println(id);
}
于 2012-03-23T22:26:08.583 回答