blob: 9f95177537ced787ff50f66b94d98db37f6f1d84 [file] [log] [blame]
Alexandria Cornwalla7cc3f12016-08-16 13:33:32 -07001/*
2 * Copyright (C) 2016 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#include "ResourceTable.h"
18#include "link/Linkers.h"
19
20#include <algorithm>
21
22namespace aapt {
23
24namespace {
25
26/**
27 * Visits each xml Node, removing URI references and nested namespaces.
28 */
29class XmlVisitor : public xml::Visitor {
30public:
31 XmlVisitor(bool keepUris) : mKeepUris(keepUris) {
32 }
33
34 void visit(xml::Element* el) override {
35 // Strip namespaces
36 for (auto& child : el->children) {
37 while (child && xml::nodeCast<xml::Namespace>(child.get())) {
38 if (child->children.empty()) {
39 child = {};
40 } else {
41 child = std::move(child->children.front());
42 child->parent = el;
43 }
44 }
45 }
46 el->children.erase(std::remove_if(el->children.begin(), el->children.end(),
47 [](const std::unique_ptr<xml::Node>& child) -> bool {
48 return child == nullptr;
49 }), el->children.end());
50
51 if (!mKeepUris) {
52 for (xml::Attribute& attr : el->attributes) {
53 attr.namespaceUri = std::string();
54 }
55 el->namespaceUri = std::string();
56 }
57 xml::Visitor::visit(el);
58 }
59
60private:
61 bool mKeepUris;
62};
63
64} // namespace
65
66bool XmlNamespaceRemover::consume(IAaptContext* context, xml::XmlResource* resource) {
67 if (!resource->root) {
68 return false;
69 }
70 // Replace any root namespaces until the root is a non-namespace node
71 while (xml::nodeCast<xml::Namespace>(resource->root.get())) {
72 if (resource->root->children.empty()) {
73 break;
74 }
75 resource->root = std::move(resource->root->children.front());
76 resource->root->parent = nullptr;
77 }
78 XmlVisitor visitor(mKeepUris);
79 resource->root->accept(&visitor);
80 return true;
81}
82
83} // namespace aapt