html 自定义标签解析,Java解析Html自定义标签的属性
想用Html.fromHtml(String, ImageGetter, TagHandler)這個方法將html文檔解析。
通過重寫handleTag(boolean opening, String tag, Editable output, XMLReader xmlReader)來解析自定義標簽,但發現沒辦法讀取標簽中的屬性。網上的找了很多方法試了都是沒有用的。查了HTML的源代碼,發現內部都是通過 attributes.getValue("", "屬性名"); 來取得屬性,但是attributes 并沒有傳遞出來。于是又開始在網上找如何取得這個attributes。
找了很久很久之后,最后在stackoverflow上找到了解決方法,
http://stackoverflow.com/questions/20788393/how-to-read-custom-html-tag-attributes-using-android-taghandler?lq=1
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
//http://stackoverflow.com/questions/6952243/how-to-get-an-attribute-from-an-xmlreader?rq=1
elementField = xmlReader.getClass().getDeclaredField("theNewElement");
elementField.setAccessible(true);
Object element = elementField.get(xmlReader);
Field attsField = element.getClass().getDeclaredField("theAtts");
attsField.setAccessible(true);
Object atts = attsField.get(element);
Field dataField = atts.getClass().getDeclaredField("data");
dataField.setAccessible(true);
String[] data = (String[])dataField.get(atts);
Field lengthField = atts.getClass().getDeclaredField("length");
lengthField.setAccessible(true);
int len = (Integer)lengthField.get(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();
}
}
}
}
總結
以上是生活随笔為你收集整理的html 自定义标签解析,Java解析Html自定义标签的属性的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: table row设置cell的html
- 下一篇: 计算机中用户权利和用户权限,揭秘:Win