如何从一个XMLReader属性属性、XMLReader

2023-09-05 07:43:03 作者:三分暖男

我有一些HTML我正在转化为跨区使用 Html.fromHtml(...) ,我有我使用的是一个自定义标签:

I have some HTML that I'm converting to a Spanned using Html.fromHtml(...), and I have a custom tag that I'm using in it:

<customtag id="1234">

所以,我已经实现了一个 TagHandler 来处理这个自定义标签,就像这样:

So I've implemented a TagHandler to handle this custom tag, like so:

public void handleTag( boolean opening, String tag, Editable output, XMLReader xmlReader ) {

    if ( tag.equalsIgnoreCase( "customtag" ) ) {

        String id = xmlReader.getProperty( "id" ).toString();
    }
}

在这种情况下,我得到一个SAX异常,因为我相信身份证字段实际上是一个属性,不是属性。但是,没有一个的getAttribute()方法的XMLReader 。所以我的问题是,我怎么使用ID字段的值,这个的XMLReader ?谢谢你。

In this case I get a SAX exception, as I believe the "id" field is actually an attribute, not a property. However, there isn't a getAttribute() method for XMLReader. So my question is, how do I get the value of the "id" field using this XMLReader? Thanks.

推荐答案

下面是我的code。通过反射来获得的XmlReader 的私有属性:

Here is my code to get the private attributes of the xmlReader by reflection:

Field 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++) {
    if("attrA".equals(data[i * 5 + 1])) {
        myAttributeA = data[i * 5 + 4];
    } else if("attrB".equals(data[i * 5 + 1])) {
        myAttributeB = data[i * 5 + 4];
    }
}

请注意,你可以把值放入一个地图,我使用的是太多的开销。

Note you could put the values into a map but for my usage that's too much overhead.