Skip to content Skip to sidebar Skip to footer

Get Org.w3c.dom.document From Xmlresourceparser

I'm planning on putting some XML files in my res/xml directory, which I want to load into Document objects (as I'm using these currently in my application and am passing them aroun

Solution 1:

Writing the code to iterate through the XMLResourceParser shows that you are a nice well-mannered developer.

However, you may be tempted to use the evil genius option.

First, create an XmlPullParser implementation that takes an XmlResourceParser in the constructor, wraps it and delegates all its methods to it -- except all the setInput-type methods. You want all those to be no-op stubs, because XmlResourceParser will throw exceptions (see XmlBlock.java, line 108 or so). Android studio can automate creating the delegate methods so you don't have to hand-code all that.

PullParserWrapperwrapper=newPullParserWrapper(
            getResources().getXml(R.xml.my_xml_file));

Note: Your wrapper class might have to have some method implementations to handle turning off namespace processing and other assorted things.

Next, you will use a org.xmlpull.v1.sax2.Driver to wrap your parser and convert it into an XMLReader:

XMLReaderxmlReader=newDriver(wrapper);

Now set up a dummy input source (the XmlResourceParser already knows where it's getting its input):

InputSourceinputSource=newInputSource(newStringReader(""));

Then you use a Transformer to convert your SAX input to a DOM output and get your result:

Transformertransformer= TransformerFactory.newInstance().newTransformer();
        DOMResultdomResult=newDOMResult();
        transformer.transform(newSAXSource(xmlReader, inputSource), domResult);
        Documentdocument= (Document) domResult.getNode();

MWAH Ha Ha Ha Ha Ha Ha!

Post a Comment for "Get Org.w3c.dom.document From Xmlresourceparser"