之前发了一篇博文《xml和实体对象相互转换 一步到位》,在项目实际应用过程中我遇到了这种xml格式:
- <?xmlversion="1.0"encoding="UTF-8"?>
- <html>
- bodydivid="div1"name="div">123</divformaction="saveForm.asp"method="post"h1>请输入您的联系信息:lable>名字:pinputtype="submit"id="btn_sub"name="btn_sub"value="Submit"/>
- inputtype="reset"id="btn_res"name="btn_res"value="Reset"form>
原来我举例用的是以下xml文件:
两个xml的区别是:
<div id="div1" name="div"/>
<div id="div1" name="div">123</div>
针对<a b="">123</a>这种类型的问题解决方案是:见代码:
修改原来的HtmlDiv:加了字段value,然后注解加了@XStreamConverter(HtmlConverter.class),HtmlConverter这是自己实现了Xstream的Converter
- @XStreamAlias("div")
- @XStreamConverter(HtmlConverter.class)
- publicclassHtmlDivimplementsBaseConverterBean{
- @XStreamAsAttribute
- privateStringid;
- privateStringname;
- privateStringvalue;
- publicStringgetId(){
- returnid;
- }
- voidsetId(Stringid){
- this.id=id;
- publicStringgetName(){
- returnname;
- voidsetName(Stringname){
- this.name=name;
- publicStringgetValue(){
- returnvalue;
- voidsetValue(Stringvalue){
- this.value=value;
- }
HtmlConverter:
classHtmlConverterimplementsConverter{
@Override
voidmarshal(Objectobj,HierarchicalStreamWriterwriter,MarshallingContextarg2){
HtmlDivdiv=(HtmlDiv)obj;
writer.setValue(div.getValue());
publicObjectunmarshal(HierarchicalStreamReaderreader,UnmarshallingContextarg1){
HtmlDivdiv=newHtmlDiv();
div.setValue(reader.getValue());
returndiv;
@SuppressWarnings("unchecked")
booleancanConvert(Classclazz){
returnclazz.equals(HtmlDiv.class);
经测试这样就能取到value的值的。
publicstaticInputFileInfo{
@XStreamAsAttribute
privateStringtype;
StringfileName;
}
@XStreamConverter(value=ToAttributedValueConverter.class,strings{"fileName})
publicstaticInputFileInfo{
@XStreamAsAttribute
privateStringtype;
StringfileName;
}