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();
               }

             }
          }
      }


   

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值