在上篇文章中,简单介绍了sax解析xml的一种方式,它是继承defaultHandler方式,并重写其中的几个方法来实现的。
接下来说的第二种方式是用RootElement这个类来解析的,RootElement 内置了defaultHandler的子类,
RootElement 源码如下:
public class RootElement extends Element { final Handler handler = new Handler(); /** * Constructs a new root element with the given name. * * @param uri the namespace * @param localName the local name */ public RootElement(String uri, String localName) { super(null, uri, localName, 0); } /** * Constructs a new root element with the given name. Uses an empty string * as the namespace. * * @param localName the local name */ public RootElement(String localName) { this("", localName); } /** * Gets the SAX {@code ContentHandler}. Pass this to your SAX parser. */ public ContentHandler getContentHandler() { return this.handler; } class Handler extends DefaultHandler { Locator locator; int depth = -1; Element current = null; StringBuilder bodyBuilder = null; @Override public void setDocumentLocator(Locator locator) { this.locator = locator; } @Override public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException { int depth = ++this.depth; if (depth == 0) { // This is the root element. startRoot(uri, localName, attributes); return; } // Prohibit mixed text and elements. if (bodyBuilder != null) { throw new BadXmlException("Encountered mixed content" + " within text element named " + current + ".", locator); } // If we're one level below the current element. if (depth == current.depth + 1) { // Look for a child to push onto the stack. Children children = current.children; if (children != null) { Element child = children.get(uri, localName); if (child != null) { start(child, attributes); } } } } void startRoot(String uri, String localName, Attributes attributes) throws SAXException { Element root = RootElement.this; if (root.uri.compareTo(uri) != 0 || root.localName.compareTo(localName) != 0) { throw new BadXmlException("Root element name does" + " not match. Expected: " + root + ", Got: " + Element.toString(uri, localName), locator); } start(root, attributes); } void start(Element e, Attributes attributes) { // Push element onto the stack. this.current = e; if (e.startElementListener != null) { e.startElementListener.start(attributes); } if (e.endTextElementListener != null) { this.bodyBuilder = new StringBuilder(); } e.resetRequiredChildren(); e.visited = true; } @Override public void characters(char[] buffer, int start, int length) throws SAXException { if (bodyBuilder != null) { bodyBuilder.append(buffer, start, length); } } @Override public void endElement(String uri, String localName, String qName) throws SAXException { Element current = this.current; // If we've ended the current element... if (depth == current.depth) { current.checkRequiredChildren(locator); // Invoke end element listener. if (current.endElementListener != null) { current.endElementListener.end(); } // Invoke end text element listener. if (bodyBuilder != null) { String body = bodyBuilder.toString(); bodyBuilder = null; // We can assume that this listener is present. current.endTextElementListener.end(body); } // Pop element off the stack. this.current = current.parent; } depth--; } } }
以上是RootElement类得源码,从源码可以看出,它只是将defaultHandler简单的处理一下。
具体应用可以参照我写的测试源码
/** * sax解析xml的第二种方式 * 用XMLReader 也是sax的一种方式 * @return */ private String saxParseSecond(){ //读取src下xml文件 InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("saxTest.xml"); SAXParserFactory factory = SAXParserFactory.newInstance(); try { SAXParser parse = factory.newSAXParser(); XMLReader reader = parse.getXMLReader(); reader.setContentHandler(getRootElement().getContentHandler()); reader.parse(new InputSource(inputStream)); } catch (ParserConfigurationException e) { e.printStackTrace(); } catch (SAXException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return result; }
/** * * @return 返回设置好处理机制的rootElement */ private RootElement getRootElement(){ /*rootElement代表着根节点,参数为根节点的tagName*/ RootElement rootElement = new RootElement("classes"); /*获取一类子节点,并为其设置相应的事件 * 这里需要注意,虽然我们只设置了一次group的事件,但是我们文档中根节点下的所有 * group却都可以触发这个事件。 * */ Element groupElement = rootElement.getChild("group"); // 读到元素开始位置时触发,如读到<group>时 groupElement.setStartElementListener(new StartElementListener() { @Override public void start(Attributes attributes) { // Log.i("TEST", "start"); String groupName = attributes.getValue("name"); String groupNum = attributes.getValue("num"); result = result+"groupName ="+groupName+"groupNum = "+groupNum+"\n"; } }); //读到元素结束位置时触发,如读到</group>时 groupElement.setEndElementListener(new EndElementListener() { @Override public void end() { } }); Element personElement = groupElement.getChild("person"); //读取<person>标签触发 personElement.setStartElementListener(new StartElementListener() { @Override public void start(Attributes attributes) { String personName = attributes.getValue("name"); String age = attributes.getValue("age"); result = result+"personName ="+personName+"age = "+age+"\n"; } }); //读取</person>标签触发 personElement.setEndElementListener(new EndElementListener() { @Override public void end() { } }); Element chinese = personElement.getChild("chinese"); // chinese.setTextElementListener(new TextElementListener() { // // @Override // public void end(String body) { // // TODO Auto-generated method stub // // } // // @Override // public void start(Attributes attributes) { // // TODO Auto-generated method stub // // } // }); // 读到文本的末尾时触发,这里的body即为文本的内容部分 chinese.setEndTextElementListener(new EndTextElementListener() { @Override public void end(String body) { Pattern p = Pattern.compile("\\s*|\t|\r|\n"); Matcher m = p.matcher(body); body = m.replaceAll(""); result = result+"chinese ="+body; } }); Element english = personElement.getChild("english"); english.setEndTextElementListener(new EndTextElementListener() { @Override public void end(String body) { Pattern p = Pattern.compile("\\s*|\t|\r|\n"); Matcher m = p.matcher(body); body = m.replaceAll(""); result = result+"english ="+body+"\n"; } }); return rootElement; }
我们都知道通过SAXParser对象解析xml的方式,这里我们又从代码中看到了利用另一个对象XMLReader进行解析,那么两者到底有什么联系和区别呢?
其实SAXParser是在SAX 1.0 定义的,而XMLReader则是在2.0中才开始出现的。你可以认为XMLReader的出现是为了替代SAXParser解析的,两者本质上干的事情是一样的,只不过XMLReader的功能更加的强悍而已。
关于XMLReader的获取方式,除了通过SAXParser的getXMLReader方法获得之外,我们还可以通过以下两种方式。
XMLReader parser=XMLReaderFactory.createXMLReader(); (1) XMLReader parser=XMLReaderFactory.createXMLReader(String className); (2)
以上就是android sax解析xml文件(二)的内容,更多相关内容请关注PHP中文网(www.php.cn)!

RSS是一種基於XML的格式,用於發布和訂閱內容。 RSS文件的XML結構包括根元素、元素和多個元素,每個代表一個內容條目。通過XML解析器讀取和解析RSS文件,用戶可以訂閱並獲取最新內容。

XML在RSS中具有結構化數據、可擴展性、跨平台兼容性和解析驗證的優勢。 1)結構化數據確保內容的一致性和可靠性;2)可擴展性允許添加自定義標籤以適應內容需求;3)跨平台兼容性使其在不同設備上無縫工作;4)解析和驗證工具確保Feed的質量和完整性。

RSS在XML中的實現方式是通過結構化的XML格式來組織內容。 1)RSS使用XML作為數據交換格式,包含頻道信息和項目列表等元素。 2)生成RSS文件需按規範組織內容,發佈到服務器供訂閱。 3)RSS文件可通過閱讀器或插件訂閱,實現內容自動更新。

RSS的高級功能包括內容命名空間、擴展模塊和條件訂閱。 1)內容命名空間擴展RSS功能,2)擴展模塊如DublinCore或iTunes添加元數據,3)條件訂閱根據特定條件篩選條目。這些功能通過添加XML元素和屬性實現,提升信息獲取效率。

RSSFEEDSUSEXMLTOSSTRUCTURECONTUPDATE.1)XMLPROVIDEDIDESAHIERARCHICALSTRUCTUREFFORDATA.2)THEELEMENTDEFINESTHEEFEED'SIDENTITYANDCONTAINS ELEMENT.3)ELEMENTEMERPREPRESERPRESENTERPRESENTIVIDIVIVELPIECTUALPIECES.4)RSSSSSSSSSSSISEXTEXTENSIBLERECTICERSINCREECTINCERINCTICENT.5)

RSS和XML是用於網絡內容管理的工具。 RSS用於發布和訂閱內容,XML用於存儲和傳輸數據。它們的工作原理包括內容髮布、訂閱和更新推送。使用示例包括RSS發布博客文章和XML存儲書籍信息。

RSS文檔是基於XML的結構化文件,用於發布和訂閱頻繁更新的內容。它的主要作用包括:1)自動化內容更新,2)內容聚合,3)提高瀏覽效率。通過RSSfeed,用戶可以訂閱並及時獲取來自不同來源的最新信息。

RSS的XML結構包括:1.XML聲明和RSS版本,2.頻道(Channel),3.條目(Item)。這些部分構成了RSS文件的基礎,允許用戶通過解析XML數據來獲取和處理內容信息。


熱AI工具

Undresser.AI Undress
人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover
用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

Video Face Swap
使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱門文章

熱工具

VSCode Windows 64位元 下載
微軟推出的免費、功能強大的一款IDE編輯器

ZendStudio 13.5.1 Mac
強大的PHP整合開發環境

MantisBT
Mantis是一個易於部署的基於Web的缺陷追蹤工具,用於幫助產品缺陷追蹤。它需要PHP、MySQL和一個Web伺服器。請查看我們的演示和託管服務。

記事本++7.3.1
好用且免費的程式碼編輯器

mPDF
mPDF是一個PHP庫,可以從UTF-8編碼的HTML產生PDF檔案。原作者Ian Back編寫mPDF以從他的網站上「即時」輸出PDF文件,並處理不同的語言。與原始腳本如HTML2FPDF相比,它的速度較慢,並且在使用Unicode字體時產生的檔案較大,但支援CSS樣式等,並進行了大量增強。支援幾乎所有語言,包括RTL(阿拉伯語和希伯來語)和CJK(中日韓)。支援嵌套的區塊級元素(如P、DIV),