Java解析Html⾃定义标签的属性
想⽤Html.fromHtml(String, ImageGetter, TagHandler)这个⽅法将html⽂档解析。
通过重写handleTag(boolean opening, String tag, Editable output, XMLReader xmlReader)来解析⾃定义标签,但发现没办法读取标签中的属性。⽹上的了很多⽅法试了都是没有⽤的。查了HTML的源代码,发现内部都是通过Value("", "属性名"); 来取得属性,但是attributes 并没有传递出来。于是⼜开始在⽹上如何取得这个attributes。
了很久很久之后,最后在stackoverflow上到了解决⽅法,
public void handleTag(boolean opening, String tag, Editable output, XMLReader xmlReader) {
if(tag.equalsIgnoreCase("myTag")) {
if (opening) {
Field elementField = null;
try {
/
/ get the private attributes of the xmlReader by reflection by rekire
//stackoverflow/questions/6952243/how-to-get-an-attribute-from-an-xmlreader?rq=1
elementField = Class().getDeclaredField("theNewElement");
java修改html文件elementField.setAccessible(true);
Object element = (xmlReader);
Field attsField = Class().getDeclaredField("theAtts");
attsField.setAccessible(true);
Object atts = (element);
Field dataField = Class().getDeclaredField("data");
dataField.setAccessible(true);
String[] data = (String[])(atts);
Field lengthField = Class().getDeclaredField("length");
lengthField.setAccessible(true);
int len = ((atts);
String myAttributeA = null;
String myAttributeB = null;
for(int i = 0; i < len; i++){
//这边的src和type换成你⾃⼰的属性名就可以了
if("src".equals(data[i * 5 + 1])) {
myAttributeA = data[i * 5 + 4];
} else if("type".equals(data[i * 5 + 1])) {
myAttributeB = data[i * 5 + 4];
}
}
Log.i("log", "src: " + myAttributeA + " type: " + myAttributeB);
} catch (NoSuchFieldException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
}
}

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。