1 /*
2  * Copyright (C) 2015 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 #ifndef AAPT_SCOPED_XML_PULL_PARSER_H
18 #define AAPT_SCOPED_XML_PULL_PARSER_H
19 
20 #include "XmlPullParser.h"
21 
22 #include <string>
23 
24 namespace aapt {
25 
26 /**
27  * An XmlPullParser that will not read past the depth
28  * of the underlying parser. When this parser is destroyed,
29  * it moves the underlying parser to the same depth it
30  * started with.
31  *
32  * You can write code like this:
33  *
34  *   while (XmlPullParser::isGoodEvent(parser.next())) {
35  *     if (parser.getEvent() != XmlPullParser::Event::StartElement) {
36  *       continue;
37  *     }
38  *
39  *     ScopedXmlPullParser scoped(parser);
40  *     if (parser.getElementName() == u"id") {
41  *       // do work.
42  *     } else {
43  *       // do nothing, as all the sub elements will be skipped
44  *       // when scoped goes out of scope.
45  *     }
46  *   }
47  */
48 class ScopedXmlPullParser : public XmlPullParser {
49 public:
50     ScopedXmlPullParser(XmlPullParser* parser);
51     ScopedXmlPullParser(const ScopedXmlPullParser&) = delete;
52     ScopedXmlPullParser& operator=(const ScopedXmlPullParser&) = delete;
53     ~ScopedXmlPullParser();
54 
55     Event getEvent() const override;
56     const std::string& getLastError() const override;
57     Event next() override;
58 
59     const std::u16string& getComment() const override;
60     size_t getLineNumber() const override;
61     size_t getDepth() const override;
62 
63     const std::u16string& getText() const override;
64 
65     const std::u16string& getNamespacePrefix() const override;
66     const std::u16string& getNamespaceUri() const override;
67     bool applyPackageAlias(std::u16string* package, const std::u16string& defaultPackage)
68             const override;
69 
70     const std::u16string& getElementNamespace() const override;
71     const std::u16string& getElementName() const override;
72 
73     const_iterator beginAttributes() const override;
74     const_iterator endAttributes() const override;
75     size_t getAttributeCount() const override;
76 
77 private:
78     XmlPullParser* mParser;
79     size_t mDepth;
80     bool mDone;
81 };
82 
83 } // namespace aapt
84 
85 #endif // AAPT_SCOPED_XML_PULL_PARSER_H
86