Simple XML 基本上不提供读取文本和元素的功能。你必须使用转换器。您可以阅读https://stackoverflow.com/questions/17462970/simpleframwork-xml-element-with-inner-text-and-child-elements回答完全相同的问题,只是它只读取一个文本。
这是在单个字符串中获取多个文本和 href 的解决方案。
首先,我为“a”标签创建了一个 A 类,使用 toString 方法打印标签,就像它在 xml 中一样:
@Root(name = "a")
public class A {
@Attribute(required = false)
private String href;
@Text
private String value;
@Override
public String toString(){
return "<a href = \"" + href + "\">" + value + "</a>";
}
}
然后是 Text 类来读取“文本”,其中需要进行转换:
@Root(name = "Text")
@Convert(Text.Parsing.class)
public class Text {
@Element
public String value;
private static class Parsing implements Converter<Text> {
// to read <a href...>
private final Serializer ser = new Persister();
@Override
public Text read(InputNode node) throws Exception {
Text t = new Text();
String s;
InputNode aref;
// read the begining of text (until first xml tag)
s = node.getValue();
if (s != null) { t.value = s; }
// read first tag (return null if no more tag in the Text)
aref = node.getNext();
while (aref != null) {
// add to the value using toString() of A class
t.value = t.value + ser.read(A.class, aref);
// read the next part of text (after the xml tag, until the next tag)
s = node.getValue();
// add to the value
if (s != null) { t.value = t.value + s; }
// read the next tag and loop
aref = node.getNext();
}
return t;
}
@Override
public void write(OutputNode node, Text value) throws Exception {
throw new UnsupportedOperationException("Not supported yet.");
}
}
}
请注意,我使用标准序列化程序读取了“a”标签,并在 A 类中添加了一个 toString 方法以将其作为 xml 字符串返回。我还没有找到直接将“a”标签作为文本读取的方法。
和主类(不要忘记将 Convert 方法映射到文本元素的反序列化的 AnnotationStrategy):
public class parseText {
public static void main(String[] args) throws Exception {
Serializer serializer = new Persister(new AnnotationStrategy());
InputStream in = ClassLoader.getSystemResourceAsStream("file.xml");
Text t = serializer.read(Text.class, in, false);
System.out.println("Texte : " + t.value);
}
}
当我将它与以下 xml 文件一起使用时:
<text>
A communications error has occurred. Please try again, or contact <a href="someURL">administrator</a>.
Alternatively, please <a href = "someURL' />">register</a>.
</text>
它给出以下结果:
Texte :
A communications error has occurred. Please try again, or contact <a href = "someURL">administrator</a>.
Alternatively, please <a href = "someURL' />">register</a>.
我希望这能帮助你解决你的问题。