如何从XMLReader获取属性



我有一些HTML,我正在使用Html.fromHtml(...)转换为Spanned,我有一个自定义标签,我在其中使用:

<customtag id="1234">

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

public void handleTag( boolean opening, String tag, Editable output, XMLReader xmlReader ) {
    if ( tag.equalsIgnoreCase( "customtag" ) ) {
        String id = xmlReader.getProperty( "id" ).toString();
    }
}

在这种情况下,我得到一个SAX异常,因为我认为"id"字段实际上是一个属性,而不是属性。然而,XMLReader没有getAttribute()方法。所以我的问题是,我如何使用这个XMLReader获得"id"字段的值?谢谢。

可以使用TagHandler提供的XmlReader,无需反射就可以访问标记属性值,但这种方法甚至比反射更不直接。诀窍是将XmlReader使用的ContentHandler替换为自定义对象。替换ContentHandler只能在调用handleTag()时完成。这就出现了获取第一个标记的属性值的问题,这个问题可以通过在html开头添加自定义标记来解决。

import android.text.Editable;
import android.text.Html;
import android.text.Spanned;
import org.xml.sax.Attributes;
import org.xml.sax.ContentHandler;
import org.xml.sax.Locator;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
import java.util.ArrayDeque;
public class HtmlParser implements Html.TagHandler, ContentHandler
{
    public interface TagHandler
    {
        boolean handleTag(boolean opening, String tag, Editable output, Attributes attributes);
    }
    public static Spanned buildSpannedText(String html, TagHandler handler)
    {
        // add a tag at the start that is not handled by default,
        // allowing custom tag handler to replace xmlReader contentHandler
        return Html.fromHtml("<inject/>" + html, null, new HtmlParser(handler));
    }
    public static String getValue(Attributes attributes, String name)
    {
        for (int i = 0, n = attributes.getLength(); i < n; i++)
        {
            if (name.equals(attributes.getLocalName(i)))
                return attributes.getValue(i);
        }
        return null;
    }
    private final TagHandler handler;
    private ContentHandler wrapped;
    private Editable text;
    private ArrayDeque<Boolean> tagStatus = new ArrayDeque<>();
    private HtmlParser(TagHandler handler)
    {
        this.handler = handler;
    }
    @Override
    public void handleTag(boolean opening, String tag, Editable output, XMLReader xmlReader)
    {
        if (wrapped == null)
        {
            // record result object
            text = output;
            // record current content handler
            wrapped = xmlReader.getContentHandler();
            // replace content handler with our own that forwards to calls to original when needed
            xmlReader.setContentHandler(this);
            // handle endElement() callback for <inject/> tag
            tagStatus.addLast(Boolean.FALSE);
        }
    }
    @Override
    public void startElement(String uri, String localName, String qName, Attributes attributes)
            throws SAXException
    {
        boolean isHandled = handler.handleTag(true, localName, text, attributes);
        tagStatus.addLast(isHandled);
        if (!isHandled)
            wrapped.startElement(uri, localName, qName, attributes);
    }
    @Override
    public void endElement(String uri, String localName, String qName) throws SAXException
    {
        if (!tagStatus.removeLast())
            wrapped.endElement(uri, localName, qName);
        handler.handleTag(false, localName, text, null);
    }
    @Override
    public void setDocumentLocator(Locator locator)
    {
        wrapped.setDocumentLocator(locator);
    }
    @Override
    public void startDocument() throws SAXException
    {
        wrapped.startDocument();
    }
    @Override
    public void endDocument() throws SAXException
    {
        wrapped.endDocument();
    }
    @Override
    public void startPrefixMapping(String prefix, String uri) throws SAXException
    {
        wrapped.startPrefixMapping(prefix, uri);
    }
    @Override
    public void endPrefixMapping(String prefix) throws SAXException
    {
        wrapped.endPrefixMapping(prefix);
    }
    @Override
    public void characters(char[] ch, int start, int length) throws SAXException
    {
        wrapped.characters(ch, start, length);
    }
    @Override
    public void ignorableWhitespace(char[] ch, int start, int length) throws SAXException
    {
        wrapped.ignorableWhitespace(ch, start, length);
    }
    @Override
    public void processingInstruction(String target, String data) throws SAXException
    {
        wrapped.processingInstruction(target, data);
    }
    @Override
    public void skippedEntity(String name) throws SAXException
    {
        wrapped.skippedEntity(name);
    }
}

有了这个类,读取属性很容易:

    HtmlParser.buildSpannedText("<x id=1 value=a>test<x id=2 value=b>", new HtmlParser.TagHandler()
    {
        @Override
        public boolean handleTag(boolean opening, String tag, Editable output, Attributes attributes)
        {
            if (opening && tag.equals("x"))
            {
                String id = HtmlParser.getValue(attributes, "id");
                String value = HtmlParser.getValue(attributes, "value");
            }
            return false;
        }
    });

这种方法的优点是它允许禁用某些标签的处理,而对其他标签使用默认处理,例如,您可以确保不创建ImageSpan对象:

    Spanned result = HtmlParser.buildSpannedText("<b><img src=nothing>test</b><img src=zilch>",
            new HtmlParser.TagHandler()
            {
                @Override
                public boolean handleTag(boolean opening, String tag, Editable output, Attributes attributes)
                {
                    // return true here to indicate that this tag was handled and
                    // should not be processed further
                    return tag.equals("img");
                }
            });

下面是我的代码,通过反射获得xmlReader的私有属性:

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];
    }
}

注意,您可以将值放入映射中,但对于我的使用来说,这样开销太大了。

根据rekire的回答,我制作了这个稍微健壮一点的解决方案,可以处理任何标签。

private TagHandler tagHandler = new TagHandler() {
    final HashMap<String, String> attributes = new HashMap<String, String>();
    private void processAttributes(final XMLReader xmlReader) {
        try {
            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);
            /**
             * MSH: Look for supported attributes and add to hash map.
             * This is as tight as things can get :)
             * The data index is "just" where the keys and values are stored. 
             */
            for(int i = 0; i < len; i++)
                attributes.put(data[i * 5 + 1], data[i * 5 + 4]);
        }
        catch (Exception e) {
            Log.d(TAG, "Exception: " + e);
        }
    }
...

And inside handleTag do:

    @Override
    public void handleTag(boolean opening, String tag, Editable output, XMLReader xmlReader) {
        processAttributes(xmlReader);
...

然后属性将被访问如下:

属性。Get ("my attribute name");

还有一个替代方案,它不允许使用自定义标记,但效果相同:

<string name="foobar">blah <annotation customTag="1234">inside blah</annotation> more blah</string>

然后像这样读:

CharSequence annotatedText = context.getText(R.string.foobar);
// wrap, because getText returns a SpannedString, which is not mutable
CharSequence processedText = replaceCustomTags(new SpannableStringBuilder(annotatedText));
public static <T extends Spannable> T replaceCustomTags(T text) {
    Annotation[] annotations = text.getSpans(0, text.length(), Annotation.class);
    for (Annotation a : annotations) {
        String attrName = a.getKey();
        if ("customTag".equals(attrName)) {
            String attrValue = a.getValue();
            int contentStart = text.getSpanStart(a);
            int contentEnd = text.getSpanEnd(a);
            int contentFlags = text.getSpanFlags(a);
            Object newFormat1 = new StyleSpan(Typeface.BOLD);
            Object newFormat2 = new ForegroundColorSpan(Color.RED);
            text.setSpan(newFormat1, contentStart, contentEnd, contentFlags);
            text.setSpan(newFormat2, contentStart, contentEnd, contentFlags);
            text.removeSpan(a);
        }
    }
    return text;
}

根据你想用你的自定义标签做什么,上面可能会帮助你。如果您只是想阅读它们,则不需要SpannableStringBuilder,只需将getText转换为Spanned接口即可进行研究。

请注意,Annotation代表<annotation foo="bar">...</annotation>是Android自API级别1以来内置的!这又是一颗隐藏的宝石。它有每个<annotation>标记一个属性的限制,但是没有什么可以阻止您嵌套多个注释来实现多个属性:

<string name="gold_admin_user"><annotation user="admin"><annotation rank="gold">$$username$$</annotation></annotation></string>

如果您使用Editable接口而不是Spannable,您还可以修改每个注释周围的内容。例如修改上面的代码:

String attrValue = a.getValue();
text.insert(text.getSpanStart(a), attrValue);
text.insert(text.getSpanStart(a) + attrValue.length(), " ");
int contentStart = text.getSpanStart(a);

的结果就像在XML中那样:

blah <b><font color="#ff0000">1234 inside blah</font></b> more blah

需要注意的一个警告是,当您进行影响文本长度的修改时,span会移动。请确保在正确的时间读取span的开始/结束索引,最好将它们内联到方法调用中。

Editable还允许您进行简单的搜索和替换替换:

index = TextUtils.indexOf(text, needle); // for example $$username$$ above
text.replace(index, index + needle.length(), replacement);

如果你需要的只是一个属性,那么旋涡的建议实际上是相当可靠的。为了给你一个简单的例子来处理它,请看这里:

<xml>Click on <user1>Johnni<user1> or <user2>Jenny<user2> to see...</<xml>

在你的自定义TagHandler中你不用等号而是用indexOf

final static String USER = "user";
if(tag.indexOf(USER) == 0) {
    // Extract tag postfix.
    String postfix = tag.substring(USER.length());
    Log.d(TAG, "postfix: " + postfix);
}

然后你可以在你的onClick视图参数传递后缀值作为一个标签,以保持它的通用。

相关内容

  • 没有找到相关文章

最新更新