XMLNode.cpp revision 19138468caf7050d482dc15f35a344eab11bb756
1//
2// Copyright 2006 The Android Open Source Project
3//
4// Build resource files from raw assets.
5//
6
7#include "XMLNode.h"
8#include "ResourceTable.h"
9
10#include <host/pseudolocalize.h>
11#include <utils/ByteOrder.h>
12#include <errno.h>
13#include <string.h>
14
15#ifndef HAVE_MS_C_RUNTIME
16#define O_BINARY 0
17#endif
18
19#define NOISY(x) //x
20#define NOISY_PARSE(x) //x
21
22const char* const RESOURCES_ROOT_NAMESPACE = "http://schemas.android.com/apk/res/";
23const char* const RESOURCES_ANDROID_NAMESPACE = "http://schemas.android.com/apk/res/android";
24const char* const RESOURCES_ROOT_PRV_NAMESPACE = "http://schemas.android.com/apk/prv/res/";
25
26const char* const XLIFF_XMLNS = "urn:oasis:names:tc:xliff:document:1.2";
27const char* const ALLOWED_XLIFF_ELEMENTS[] = {
28        "bpt",
29        "ept",
30        "it",
31        "ph",
32        "g",
33        "bx",
34        "ex",
35        "x"
36    };
37
38bool isWhitespace(const char16_t* str)
39{
40    while (*str != 0 && *str < 128 && isspace(*str)) {
41        str++;
42    }
43    return *str == 0;
44}
45
46static const String16 RESOURCES_PREFIX(RESOURCES_ROOT_NAMESPACE);
47static const String16 RESOURCES_PRV_PREFIX(RESOURCES_ROOT_PRV_NAMESPACE);
48
49String16 getNamespaceResourcePackage(String16 namespaceUri, bool* outIsPublic)
50{
51    //printf("%s starts with %s?\n", String8(namespaceUri).string(),
52    //       String8(RESOURCES_PREFIX).string());
53    size_t prefixSize;
54    bool isPublic = true;
55    if (namespaceUri.startsWith(RESOURCES_PREFIX)) {
56        prefixSize = RESOURCES_PREFIX.size();
57    } else if (namespaceUri.startsWith(RESOURCES_PRV_PREFIX)) {
58        isPublic = false;
59        prefixSize = RESOURCES_PRV_PREFIX.size();
60    } else {
61        if (outIsPublic) *outIsPublic = isPublic; // = true
62        return String16();
63    }
64
65    //printf("YES!\n");
66    //printf("namespace: %s\n", String8(String16(namespaceUri, namespaceUri.size()-prefixSize, prefixSize)).string());
67    if (outIsPublic) *outIsPublic = isPublic;
68    return String16(namespaceUri, namespaceUri.size()-prefixSize, prefixSize);
69}
70
71status_t parseStyledString(Bundle* bundle,
72                           const char* fileName,
73                           ResXMLTree* inXml,
74                           const String16& endTag,
75                           String16* outString,
76                           Vector<StringPool::entry_style_span>* outSpans,
77                           bool pseudolocalize)
78{
79    Vector<StringPool::entry_style_span> spanStack;
80    String16 curString;
81    String16 rawString;
82    const char* errorMsg;
83    int xliffDepth = 0;
84    bool firstTime = true;
85
86    size_t len;
87    ResXMLTree::event_code_t code;
88    while ((code=inXml->next()) != ResXMLTree::END_DOCUMENT && code != ResXMLTree::BAD_DOCUMENT) {
89
90        if (code == ResXMLTree::TEXT) {
91            String16 text(inXml->getText(&len));
92            if (firstTime && text.size() > 0) {
93                firstTime = false;
94                if (text.string()[0] == '@') {
95                    // If this is a resource reference, don't do the pseudoloc.
96                    pseudolocalize = false;
97                }
98            }
99            if (xliffDepth == 0 && pseudolocalize) {
100                std::string orig(String8(text).string());
101                std::string pseudo = pseudolocalize_string(orig);
102                curString.append(String16(String8(pseudo.c_str())));
103            } else {
104                curString.append(text);
105            }
106        } else if (code == ResXMLTree::START_TAG) {
107            const String16 element16(inXml->getElementName(&len));
108            const String8 element8(element16);
109
110            size_t nslen;
111            const uint16_t* ns = inXml->getElementNamespace(&nslen);
112            if (ns == NULL) {
113                ns = (const uint16_t*)"\0\0";
114                nslen = 0;
115            }
116            const String8 nspace(String16(ns, nslen));
117            if (nspace == XLIFF_XMLNS) {
118                const int N = sizeof(ALLOWED_XLIFF_ELEMENTS)/sizeof(ALLOWED_XLIFF_ELEMENTS[0]);
119                for (int i=0; i<N; i++) {
120                    if (element8 == ALLOWED_XLIFF_ELEMENTS[i]) {
121                        xliffDepth++;
122                        // in this case, treat it like it was just text, in other words, do nothing
123                        // here and silently drop this element
124                        goto moveon;
125                    }
126                }
127                {
128                    SourcePos(String8(fileName), inXml->getLineNumber()).error(
129                            "Found unsupported XLIFF tag <%s>\n",
130                            element8.string());
131                    return UNKNOWN_ERROR;
132                }
133moveon:
134                continue;
135            }
136
137            if (outSpans == NULL) {
138                SourcePos(String8(fileName), inXml->getLineNumber()).error(
139                        "Found style tag <%s> where styles are not allowed\n", element8.string());
140                return UNKNOWN_ERROR;
141            }
142
143            if (!ResTable::collectString(outString, curString.string(),
144                                         curString.size(), false, &errorMsg, true)) {
145                SourcePos(String8(fileName), inXml->getLineNumber()).error("%s (in %s)\n",
146                        errorMsg, String8(curString).string());
147                return UNKNOWN_ERROR;
148            }
149            rawString.append(curString);
150            curString = String16();
151
152            StringPool::entry_style_span span;
153            span.name = element16;
154            for (size_t ai=0; ai<inXml->getAttributeCount(); ai++) {
155                span.name.append(String16(";"));
156                const char16_t* str = inXml->getAttributeName(ai, &len);
157                span.name.append(str, len);
158                span.name.append(String16("="));
159                str = inXml->getAttributeStringValue(ai, &len);
160                span.name.append(str, len);
161            }
162            //printf("Span: %s\n", String8(span.name).string());
163            span.span.firstChar = span.span.lastChar = outString->size();
164            spanStack.push(span);
165
166        } else if (code == ResXMLTree::END_TAG) {
167            size_t nslen;
168            const uint16_t* ns = inXml->getElementNamespace(&nslen);
169            if (ns == NULL) {
170                ns = (const uint16_t*)"\0\0";
171                nslen = 0;
172            }
173            const String8 nspace(String16(ns, nslen));
174            if (nspace == XLIFF_XMLNS) {
175                xliffDepth--;
176                continue;
177            }
178            if (!ResTable::collectString(outString, curString.string(),
179                                         curString.size(), false, &errorMsg, true)) {
180                SourcePos(String8(fileName), inXml->getLineNumber()).error("%s (in %s)\n",
181                        errorMsg, String8(curString).string());
182                return UNKNOWN_ERROR;
183            }
184            rawString.append(curString);
185            curString = String16();
186
187            if (spanStack.size() == 0) {
188                if (strcmp16(inXml->getElementName(&len), endTag.string()) != 0) {
189                    SourcePos(String8(fileName), inXml->getLineNumber()).error(
190                            "Found tag %s where <%s> close is expected\n",
191                            String8(inXml->getElementName(&len)).string(),
192                            String8(endTag).string());
193                    return UNKNOWN_ERROR;
194                }
195                break;
196            }
197            StringPool::entry_style_span span = spanStack.top();
198            String16 spanTag;
199            ssize_t semi = span.name.findFirst(';');
200            if (semi >= 0) {
201                spanTag.setTo(span.name.string(), semi);
202            } else {
203                spanTag.setTo(span.name);
204            }
205            if (strcmp16(inXml->getElementName(&len), spanTag.string()) != 0) {
206                SourcePos(String8(fileName), inXml->getLineNumber()).error(
207                        "Found close tag %s where close tag %s is expected\n",
208                        String8(inXml->getElementName(&len)).string(),
209                        String8(spanTag).string());
210                return UNKNOWN_ERROR;
211            }
212            bool empty = true;
213            if (outString->size() > 0) {
214                span.span.lastChar = outString->size()-1;
215                if (span.span.lastChar >= span.span.firstChar) {
216                    empty = false;
217                    outSpans->add(span);
218                }
219            }
220            spanStack.pop();
221
222            /*
223             * This warning seems to be just an irritation to most people,
224             * since it is typically introduced by translators who then never
225             * see the warning.
226             */
227            if (0 && empty) {
228                fprintf(stderr, "%s:%d: warning: empty '%s' span found in text '%s'\n",
229                        fileName, inXml->getLineNumber(),
230                        String8(spanTag).string(), String8(*outString).string());
231
232            }
233        } else if (code == ResXMLTree::START_NAMESPACE) {
234            // nothing
235        }
236    }
237
238    if (code == ResXMLTree::BAD_DOCUMENT) {
239            SourcePos(String8(fileName), inXml->getLineNumber()).error(
240                    "Error parsing XML\n");
241    }
242
243    if (outSpans != NULL && outSpans->size() > 0) {
244        if (curString.size() > 0) {
245            if (!ResTable::collectString(outString, curString.string(),
246                                         curString.size(), false, &errorMsg, true)) {
247                SourcePos(String8(fileName), inXml->getLineNumber()).error(
248                        "%s (in %s)\n",
249                        errorMsg, String8(curString).string());
250                return UNKNOWN_ERROR;
251            }
252        }
253    } else {
254        // There is no style information, so string processing will happen
255        // later as part of the overall type conversion.  Return to the
256        // client the raw unprocessed text.
257        rawString.append(curString);
258        outString->setTo(rawString);
259    }
260
261    return NO_ERROR;
262}
263
264struct namespace_entry {
265    String8 prefix;
266    String8 uri;
267};
268
269static String8 make_prefix(int depth)
270{
271    String8 prefix;
272    int i;
273    for (i=0; i<depth; i++) {
274        prefix.append("  ");
275    }
276    return prefix;
277}
278
279static String8 build_namespace(const Vector<namespace_entry>& namespaces,
280        const uint16_t* ns)
281{
282    String8 str;
283    if (ns != NULL) {
284        str = String8(ns);
285        const size_t N = namespaces.size();
286        for (size_t i=0; i<N; i++) {
287            const namespace_entry& ne = namespaces.itemAt(i);
288            if (ne.uri == str) {
289                str = ne.prefix;
290                break;
291            }
292        }
293        str.append(":");
294    }
295    return str;
296}
297
298void printXMLBlock(ResXMLTree* block)
299{
300    block->restart();
301
302    Vector<namespace_entry> namespaces;
303
304    ResXMLTree::event_code_t code;
305    int depth = 0;
306    while ((code=block->next()) != ResXMLTree::END_DOCUMENT && code != ResXMLTree::BAD_DOCUMENT) {
307        String8 prefix = make_prefix(depth);
308        int i;
309        if (code == ResXMLTree::START_TAG) {
310            size_t len;
311            const uint16_t* ns16 = block->getElementNamespace(&len);
312            String8 elemNs = build_namespace(namespaces, ns16);
313            const uint16_t* com16 = block->getComment(&len);
314            if (com16) {
315                printf("%s <!-- %s -->\n", prefix.string(), String8(com16).string());
316            }
317            printf("%sE: %s%s (line=%d)\n", prefix.string(), elemNs.string(),
318                   String8(block->getElementName(&len)).string(),
319                   block->getLineNumber());
320            int N = block->getAttributeCount();
321            depth++;
322            prefix = make_prefix(depth);
323            for (i=0; i<N; i++) {
324                uint32_t res = block->getAttributeNameResID(i);
325                ns16 = block->getAttributeNamespace(i, &len);
326                String8 ns = build_namespace(namespaces, ns16);
327                String8 name(block->getAttributeName(i, &len));
328                printf("%sA: ", prefix.string());
329                if (res) {
330                    printf("%s%s(0x%08x)", ns.string(), name.string(), res);
331                } else {
332                    printf("%s%s", ns.string(), name.string());
333                }
334                Res_value value;
335                block->getAttributeValue(i, &value);
336                if (value.dataType == Res_value::TYPE_NULL) {
337                    printf("=(null)");
338                } else if (value.dataType == Res_value::TYPE_REFERENCE) {
339                    printf("=@0x%x", (int)value.data);
340                } else if (value.dataType == Res_value::TYPE_ATTRIBUTE) {
341                    printf("=?0x%x", (int)value.data);
342                } else if (value.dataType == Res_value::TYPE_STRING) {
343                    printf("=\"%s\"",
344                           String8(block->getAttributeStringValue(i, &len)).string());
345                } else {
346                    printf("=(type 0x%x)0x%x", (int)value.dataType, (int)value.data);
347                }
348                const char16_t* val = block->getAttributeStringValue(i, &len);
349                if (val != NULL) {
350                    printf(" (Raw: \"%s\")", String8(val).string());
351                }
352                printf("\n");
353            }
354        } else if (code == ResXMLTree::END_TAG) {
355            depth--;
356        } else if (code == ResXMLTree::START_NAMESPACE) {
357            namespace_entry ns;
358            size_t len;
359            const uint16_t* prefix16 = block->getNamespacePrefix(&len);
360            if (prefix16) {
361                ns.prefix = String8(prefix16);
362            } else {
363                ns.prefix = "<DEF>";
364            }
365            ns.uri = String8(block->getNamespaceUri(&len));
366            namespaces.push(ns);
367            printf("%sN: %s=%s\n", prefix.string(), ns.prefix.string(),
368                    ns.uri.string());
369            depth++;
370        } else if (code == ResXMLTree::END_NAMESPACE) {
371            depth--;
372            const namespace_entry& ns = namespaces.top();
373            size_t len;
374            const uint16_t* prefix16 = block->getNamespacePrefix(&len);
375            String8 pr;
376            if (prefix16) {
377                pr = String8(prefix16);
378            } else {
379                pr = "<DEF>";
380            }
381            if (ns.prefix != pr) {
382                prefix = make_prefix(depth);
383                printf("%s*** BAD END NS PREFIX: found=%s, expected=%s\n",
384                        prefix.string(), pr.string(), ns.prefix.string());
385            }
386            String8 uri = String8(block->getNamespaceUri(&len));
387            if (ns.uri != uri) {
388                prefix = make_prefix(depth);
389                printf("%s *** BAD END NS URI: found=%s, expected=%s\n",
390                        prefix.string(), uri.string(), ns.uri.string());
391            }
392            namespaces.pop();
393        } else if (code == ResXMLTree::TEXT) {
394            size_t len;
395            printf("%sC: \"%s\"\n", prefix.string(), String8(block->getText(&len)).string());
396        }
397    }
398
399    block->restart();
400}
401
402status_t parseXMLResource(const sp<AaptFile>& file, ResXMLTree* outTree,
403                          bool stripAll, bool keepComments,
404                          const char** cDataTags)
405{
406    sp<XMLNode> root = XMLNode::parse(file);
407    if (root == NULL) {
408        return UNKNOWN_ERROR;
409    }
410    root->removeWhitespace(stripAll, cDataTags);
411
412    NOISY(printf("Input XML from %s:\n", (const char*)file->getPrintableSource()));
413    NOISY(root->print());
414    sp<AaptFile> rsc = new AaptFile(String8(), AaptGroupEntry(), String8());
415    status_t err = root->flatten(rsc, !keepComments, false);
416    if (err != NO_ERROR) {
417        return err;
418    }
419    err = outTree->setTo(rsc->getData(), rsc->getSize(), true);
420    if (err != NO_ERROR) {
421        return err;
422    }
423
424    NOISY(printf("Output XML:\n"));
425    NOISY(printXMLBlock(outTree));
426
427    return NO_ERROR;
428}
429
430sp<XMLNode> XMLNode::parse(const sp<AaptFile>& file)
431{
432    char buf[16384];
433    int fd = open(file->getSourceFile().string(), O_RDONLY | O_BINARY);
434    if (fd < 0) {
435        SourcePos(file->getSourceFile(), -1).error("Unable to open file for read: %s",
436                strerror(errno));
437        return NULL;
438    }
439
440    XML_Parser parser = XML_ParserCreateNS(NULL, 1);
441    ParseState state;
442    state.filename = file->getPrintableSource();
443    state.parser = parser;
444    XML_SetUserData(parser, &state);
445    XML_SetElementHandler(parser, startElement, endElement);
446    XML_SetNamespaceDeclHandler(parser, startNamespace, endNamespace);
447    XML_SetCharacterDataHandler(parser, characterData);
448    XML_SetCommentHandler(parser, commentData);
449
450    ssize_t len;
451    bool done;
452    do {
453        len = read(fd, buf, sizeof(buf));
454        done = len < (ssize_t)sizeof(buf);
455        if (len < 0) {
456            SourcePos(file->getSourceFile(), -1).error("Error reading file: %s\n", strerror(errno));
457            close(fd);
458            return NULL;
459        }
460        if (XML_Parse(parser, buf, len, done) == XML_STATUS_ERROR) {
461            SourcePos(file->getSourceFile(), (int)XML_GetCurrentLineNumber(parser)).error(
462                    "Error parsing XML: %s\n", XML_ErrorString(XML_GetErrorCode(parser)));
463            close(fd);
464            return NULL;
465        }
466    } while (!done);
467
468    XML_ParserFree(parser);
469    if (state.root == NULL) {
470        SourcePos(file->getSourceFile(), -1).error("No XML data generated when parsing");
471    }
472    close(fd);
473    return state.root;
474}
475
476XMLNode::XMLNode(const String8& filename, const String16& s1, const String16& s2, bool isNamespace)
477    : mNextAttributeIndex(0x80000000)
478    , mFilename(filename)
479    , mStartLineNumber(0)
480    , mEndLineNumber(0)
481    , mUTF8(false)
482{
483    if (isNamespace) {
484        mNamespacePrefix = s1;
485        mNamespaceUri = s2;
486    } else {
487        mNamespaceUri = s1;
488        mElementName = s2;
489    }
490}
491
492XMLNode::XMLNode(const String8& filename)
493    : mFilename(filename)
494{
495    memset(&mCharsValue, 0, sizeof(mCharsValue));
496}
497
498XMLNode::type XMLNode::getType() const
499{
500    if (mElementName.size() != 0) {
501        return TYPE_ELEMENT;
502    }
503    if (mNamespaceUri.size() != 0) {
504        return TYPE_NAMESPACE;
505    }
506    return TYPE_CDATA;
507}
508
509const String16& XMLNode::getNamespacePrefix() const
510{
511    return mNamespacePrefix;
512}
513
514const String16& XMLNode::getNamespaceUri() const
515{
516    return mNamespaceUri;
517}
518
519const String16& XMLNode::getElementNamespace() const
520{
521    return mNamespaceUri;
522}
523
524const String16& XMLNode::getElementName() const
525{
526    return mElementName;
527}
528
529const Vector<sp<XMLNode> >& XMLNode::getChildren() const
530{
531    return mChildren;
532}
533
534const String8& XMLNode::getFilename() const
535{
536    return mFilename;
537}
538
539const Vector<XMLNode::attribute_entry>&
540    XMLNode::getAttributes() const
541{
542    return mAttributes;
543}
544
545const XMLNode::attribute_entry* XMLNode::getAttribute(const String16& ns,
546        const String16& name) const
547{
548    for (size_t i=0; i<mAttributes.size(); i++) {
549        const attribute_entry& ae(mAttributes.itemAt(i));
550        if (ae.ns == ns && ae.name == name) {
551            return &ae;
552        }
553    }
554
555    return NULL;
556}
557
558const String16& XMLNode::getCData() const
559{
560    return mChars;
561}
562
563const String16& XMLNode::getComment() const
564{
565    return mComment;
566}
567
568int32_t XMLNode::getStartLineNumber() const
569{
570    return mStartLineNumber;
571}
572
573int32_t XMLNode::getEndLineNumber() const
574{
575    return mEndLineNumber;
576}
577
578sp<XMLNode> XMLNode::searchElement(const String16& tagNamespace, const String16& tagName)
579{
580    if (getType() == XMLNode::TYPE_ELEMENT
581            && mNamespaceUri == tagNamespace
582            && mElementName == tagName) {
583        return this;
584    }
585
586    for (size_t i=0; i<mChildren.size(); i++) {
587        sp<XMLNode> found = mChildren.itemAt(i)->searchElement(tagNamespace, tagName);
588        if (found != NULL) {
589            return found;
590        }
591    }
592
593    return NULL;
594}
595
596sp<XMLNode> XMLNode::getChildElement(const String16& tagNamespace, const String16& tagName)
597{
598    for (size_t i=0; i<mChildren.size(); i++) {
599        sp<XMLNode> child = mChildren.itemAt(i);
600        if (child->getType() == XMLNode::TYPE_ELEMENT
601                && child->mNamespaceUri == tagNamespace
602                && child->mElementName == tagName) {
603            return child;
604        }
605    }
606
607    return NULL;
608}
609
610status_t XMLNode::addChild(const sp<XMLNode>& child)
611{
612    if (getType() == TYPE_CDATA) {
613        SourcePos(mFilename, child->getStartLineNumber()).error("Child to CDATA node.");
614        return UNKNOWN_ERROR;
615    }
616    //printf("Adding child %p to parent %p\n", child.get(), this);
617    mChildren.add(child);
618    return NO_ERROR;
619}
620
621status_t XMLNode::insertChildAt(const sp<XMLNode>& child, size_t index)
622{
623    if (getType() == TYPE_CDATA) {
624        SourcePos(mFilename, child->getStartLineNumber()).error("Child to CDATA node.");
625        return UNKNOWN_ERROR;
626    }
627    //printf("Adding child %p to parent %p\n", child.get(), this);
628    mChildren.insertAt(child, index);
629    return NO_ERROR;
630}
631
632status_t XMLNode::addAttribute(const String16& ns, const String16& name,
633                               const String16& value)
634{
635    if (getType() == TYPE_CDATA) {
636        SourcePos(mFilename, getStartLineNumber()).error("Child to CDATA node.");
637        return UNKNOWN_ERROR;
638    }
639    attribute_entry e;
640    e.index = mNextAttributeIndex++;
641    e.ns = ns;
642    e.name = name;
643    e.string = value;
644    mAttributes.add(e);
645    mAttributeOrder.add(e.index, mAttributes.size()-1);
646    return NO_ERROR;
647}
648
649void XMLNode::setAttributeResID(size_t attrIdx, uint32_t resId)
650{
651    attribute_entry& e = mAttributes.editItemAt(attrIdx);
652    if (e.nameResId) {
653        mAttributeOrder.removeItem(e.nameResId);
654    } else {
655        mAttributeOrder.removeItem(e.index);
656    }
657    NOISY(printf("Elem %s %s=\"%s\": set res id = 0x%08x\n",
658            String8(getElementName()).string(),
659            String8(mAttributes.itemAt(attrIdx).name).string(),
660            String8(mAttributes.itemAt(attrIdx).string).string(),
661            resId));
662    mAttributes.editItemAt(attrIdx).nameResId = resId;
663    mAttributeOrder.add(resId, attrIdx);
664}
665
666status_t XMLNode::appendChars(const String16& chars)
667{
668    if (getType() != TYPE_CDATA) {
669        SourcePos(mFilename, getStartLineNumber()).error("Adding characters to element node.");
670        return UNKNOWN_ERROR;
671    }
672    mChars.append(chars);
673    return NO_ERROR;
674}
675
676status_t XMLNode::appendComment(const String16& comment)
677{
678    if (mComment.size() > 0) {
679        mComment.append(String16("\n"));
680    }
681    mComment.append(comment);
682    return NO_ERROR;
683}
684
685void XMLNode::setStartLineNumber(int32_t line)
686{
687    mStartLineNumber = line;
688}
689
690void XMLNode::setEndLineNumber(int32_t line)
691{
692    mEndLineNumber = line;
693}
694
695void XMLNode::removeWhitespace(bool stripAll, const char** cDataTags)
696{
697    //printf("Removing whitespace in %s\n", String8(mElementName).string());
698    size_t N = mChildren.size();
699    if (cDataTags) {
700        String8 tag(mElementName);
701        const char** p = cDataTags;
702        while (*p) {
703            if (tag == *p) {
704                stripAll = false;
705                break;
706            }
707        }
708    }
709    for (size_t i=0; i<N; i++) {
710        sp<XMLNode> node = mChildren.itemAt(i);
711        if (node->getType() == TYPE_CDATA) {
712            // This is a CDATA node...
713            const char16_t* p = node->mChars.string();
714            while (*p != 0 && *p < 128 && isspace(*p)) {
715                p++;
716            }
717            //printf("Space ends at %d in \"%s\"\n",
718            //       (int)(p-node->mChars.string()),
719            //       String8(node->mChars).string());
720            if (*p == 0) {
721                if (stripAll) {
722                    // Remove this node!
723                    mChildren.removeAt(i);
724                    N--;
725                    i--;
726                } else {
727                    node->mChars = String16(" ");
728                }
729            } else {
730                // Compact leading/trailing whitespace.
731                const char16_t* e = node->mChars.string()+node->mChars.size()-1;
732                while (e > p && *e < 128 && isspace(*e)) {
733                    e--;
734                }
735                if (p > node->mChars.string()) {
736                    p--;
737                }
738                if (e < (node->mChars.string()+node->mChars.size()-1)) {
739                    e++;
740                }
741                if (p > node->mChars.string() ||
742                    e < (node->mChars.string()+node->mChars.size()-1)) {
743                    String16 tmp(p, e-p+1);
744                    node->mChars = tmp;
745                }
746            }
747        } else {
748            node->removeWhitespace(stripAll, cDataTags);
749        }
750    }
751}
752
753status_t XMLNode::parseValues(const sp<AaptAssets>& assets,
754                              ResourceTable* table)
755{
756    bool hasErrors = false;
757
758    if (getType() == TYPE_ELEMENT) {
759        const size_t N = mAttributes.size();
760        String16 defPackage(assets->getPackage());
761        for (size_t i=0; i<N; i++) {
762            attribute_entry& e = mAttributes.editItemAt(i);
763            AccessorCookie ac(SourcePos(mFilename, getStartLineNumber()), String8(e.name),
764                    String8(e.string));
765            table->setCurrentXmlPos(SourcePos(mFilename, getStartLineNumber()));
766            if (!assets->getIncludedResources()
767                    .stringToValue(&e.value, &e.string,
768                                  e.string.string(), e.string.size(), true, true,
769                                  e.nameResId, NULL, &defPackage, table, &ac)) {
770                hasErrors = true;
771            }
772            NOISY(printf("Attr %s: type=0x%x, str=%s\n",
773                   String8(e.name).string(), e.value.dataType,
774                   String8(e.string).string()));
775        }
776    }
777    const size_t N = mChildren.size();
778    for (size_t i=0; i<N; i++) {
779        status_t err = mChildren.itemAt(i)->parseValues(assets, table);
780        if (err != NO_ERROR) {
781            hasErrors = true;
782        }
783    }
784    return hasErrors ? UNKNOWN_ERROR : NO_ERROR;
785}
786
787status_t XMLNode::assignResourceIds(const sp<AaptAssets>& assets,
788                                    const ResourceTable* table)
789{
790    bool hasErrors = false;
791
792    if (getType() == TYPE_ELEMENT) {
793        String16 attr("attr");
794        const char* errorMsg;
795        const size_t N = mAttributes.size();
796        for (size_t i=0; i<N; i++) {
797            const attribute_entry& e = mAttributes.itemAt(i);
798            if (e.ns.size() <= 0) continue;
799            bool nsIsPublic;
800            String16 pkg(getNamespaceResourcePackage(e.ns, &nsIsPublic));
801            NOISY(printf("Elem %s %s=\"%s\": namespace(%s) %s ===> %s\n",
802                    String8(getElementName()).string(),
803                    String8(e.name).string(),
804                    String8(e.string).string(),
805                    String8(e.ns).string(),
806                    (nsIsPublic) ? "public" : "private",
807                    String8(pkg).string()));
808            if (pkg.size() <= 0) continue;
809            uint32_t res = table != NULL
810                ? table->getResId(e.name, &attr, &pkg, &errorMsg, nsIsPublic)
811                : assets->getIncludedResources().
812                    identifierForName(e.name.string(), e.name.size(),
813                                      attr.string(), attr.size(),
814                                      pkg.string(), pkg.size());
815            if (res != 0) {
816                NOISY(printf("XML attribute name %s: resid=0x%08x\n",
817                             String8(e.name).string(), res));
818                setAttributeResID(i, res);
819            } else {
820                SourcePos(mFilename, getStartLineNumber()).error(
821                        "No resource identifier found for attribute '%s' in package '%s'\n",
822                        String8(e.name).string(), String8(pkg).string());
823                hasErrors = true;
824            }
825        }
826    }
827    const size_t N = mChildren.size();
828    for (size_t i=0; i<N; i++) {
829        status_t err = mChildren.itemAt(i)->assignResourceIds(assets, table);
830        if (err < NO_ERROR) {
831            hasErrors = true;
832        }
833    }
834
835    return hasErrors ? UNKNOWN_ERROR : NO_ERROR;
836}
837
838status_t XMLNode::flatten(const sp<AaptFile>& dest,
839        bool stripComments, bool stripRawValues) const
840{
841    StringPool strings = StringPool(false, mUTF8);
842    Vector<uint32_t> resids;
843
844    // First collect just the strings for attribute names that have a
845    // resource ID assigned to them.  This ensures that the resource ID
846    // array is compact, and makes it easier to deal with attribute names
847    // in different namespaces (and thus with different resource IDs).
848    collect_resid_strings(&strings, &resids);
849
850    // Next collect all remainibng strings.
851    collect_strings(&strings, &resids, stripComments, stripRawValues);
852
853#if 0  // No longer compiles
854    NOISY(printf("Found strings:\n");
855        const size_t N = strings.size();
856        for (size_t i=0; i<N; i++) {
857            printf("%s\n", String8(strings.entryAt(i).string).string());
858        }
859    );
860#endif
861
862    sp<AaptFile> stringPool = strings.createStringBlock();
863    NOISY(aout << "String pool:"
864          << HexDump(stringPool->getData(), stringPool->getSize()) << endl);
865
866    ResXMLTree_header header;
867    memset(&header, 0, sizeof(header));
868    header.header.type = htods(RES_XML_TYPE);
869    header.header.headerSize = htods(sizeof(header));
870
871    const size_t basePos = dest->getSize();
872    dest->writeData(&header, sizeof(header));
873    dest->writeData(stringPool->getData(), stringPool->getSize());
874
875    // If we have resource IDs, write them.
876    if (resids.size() > 0) {
877        const size_t resIdsPos = dest->getSize();
878        const size_t resIdsSize =
879            sizeof(ResChunk_header)+(sizeof(uint32_t)*resids.size());
880        ResChunk_header* idsHeader = (ResChunk_header*)
881            (((const uint8_t*)dest->editData(resIdsPos+resIdsSize))+resIdsPos);
882        idsHeader->type = htods(RES_XML_RESOURCE_MAP_TYPE);
883        idsHeader->headerSize = htods(sizeof(*idsHeader));
884        idsHeader->size = htodl(resIdsSize);
885        uint32_t* ids = (uint32_t*)(idsHeader+1);
886        for (size_t i=0; i<resids.size(); i++) {
887            *ids++ = htodl(resids[i]);
888        }
889    }
890
891    flatten_node(strings, dest, stripComments, stripRawValues);
892
893    void* data = dest->editData();
894    ResXMLTree_header* hd = (ResXMLTree_header*)(((uint8_t*)data)+basePos);
895    size_t size = dest->getSize()-basePos;
896    hd->header.size = htodl(dest->getSize()-basePos);
897
898    NOISY(aout << "XML resource:"
899          << HexDump(dest->getData(), dest->getSize()) << endl);
900
901    #if PRINT_STRING_METRICS
902    fprintf(stderr, "**** total xml size: %d / %d%% strings (in %s)\n",
903        dest->getSize(), (stringPool->getSize()*100)/dest->getSize(),
904        dest->getPath().string());
905    #endif
906
907    return NO_ERROR;
908}
909
910void XMLNode::print(int indent)
911{
912    String8 prefix;
913    int i;
914    for (i=0; i<indent; i++) {
915        prefix.append("  ");
916    }
917    if (getType() == TYPE_ELEMENT) {
918        String8 elemNs(getNamespaceUri());
919        if (elemNs.size() > 0) {
920            elemNs.append(":");
921        }
922        printf("%s E: %s%s", prefix.string(),
923               elemNs.string(), String8(getElementName()).string());
924        int N = mAttributes.size();
925        for (i=0; i<N; i++) {
926            ssize_t idx = mAttributeOrder.valueAt(i);
927            if (i == 0) {
928                printf(" / ");
929            } else {
930                printf(", ");
931            }
932            const attribute_entry& attr = mAttributes.itemAt(idx);
933            String8 attrNs(attr.ns);
934            if (attrNs.size() > 0) {
935                attrNs.append(":");
936            }
937            if (attr.nameResId) {
938                printf("%s%s(0x%08x)", attrNs.string(),
939                       String8(attr.name).string(), attr.nameResId);
940            } else {
941                printf("%s%s", attrNs.string(), String8(attr.name).string());
942            }
943            printf("=%s", String8(attr.string).string());
944        }
945        printf("\n");
946    } else if (getType() == TYPE_NAMESPACE) {
947        printf("%s N: %s=%s\n", prefix.string(),
948               getNamespacePrefix().size() > 0
949                    ? String8(getNamespacePrefix()).string() : "<DEF>",
950               String8(getNamespaceUri()).string());
951    } else {
952        printf("%s C: \"%s\"\n", prefix.string(), String8(getCData()).string());
953    }
954    int N = mChildren.size();
955    for (i=0; i<N; i++) {
956        mChildren.itemAt(i)->print(indent+1);
957    }
958}
959
960static void splitName(const char* name, String16* outNs, String16* outName)
961{
962    const char* p = name;
963    while (*p != 0 && *p != 1) {
964        p++;
965    }
966    if (*p == 0) {
967        *outNs = String16();
968        *outName = String16(name);
969    } else {
970        *outNs = String16(name, (p-name));
971        *outName = String16(p+1);
972    }
973}
974
975void XMLCALL
976XMLNode::startNamespace(void *userData, const char *prefix, const char *uri)
977{
978    NOISY_PARSE(printf("Start Namespace: %s %s\n", prefix, uri));
979    ParseState* st = (ParseState*)userData;
980    sp<XMLNode> node = XMLNode::newNamespace(st->filename,
981            String16(prefix != NULL ? prefix : ""), String16(uri));
982    node->setStartLineNumber(XML_GetCurrentLineNumber(st->parser));
983    if (st->stack.size() > 0) {
984        st->stack.itemAt(st->stack.size()-1)->addChild(node);
985    } else {
986        st->root = node;
987    }
988    st->stack.push(node);
989}
990
991void XMLCALL
992XMLNode::startElement(void *userData, const char *name, const char **atts)
993{
994    NOISY_PARSE(printf("Start Element: %s\n", name));
995    ParseState* st = (ParseState*)userData;
996    String16 ns16, name16;
997    splitName(name, &ns16, &name16);
998    sp<XMLNode> node = XMLNode::newElement(st->filename, ns16, name16);
999    node->setStartLineNumber(XML_GetCurrentLineNumber(st->parser));
1000    if (st->pendingComment.size() > 0) {
1001        node->appendComment(st->pendingComment);
1002        st->pendingComment = String16();
1003    }
1004    if (st->stack.size() > 0) {
1005        st->stack.itemAt(st->stack.size()-1)->addChild(node);
1006    } else {
1007        st->root = node;
1008    }
1009    st->stack.push(node);
1010
1011    for (int i = 0; atts[i]; i += 2) {
1012        splitName(atts[i], &ns16, &name16);
1013        node->addAttribute(ns16, name16, String16(atts[i+1]));
1014    }
1015}
1016
1017void XMLCALL
1018XMLNode::characterData(void *userData, const XML_Char *s, int len)
1019{
1020    NOISY_PARSE(printf("CDATA: \"%s\"\n", String8(s, len).string()));
1021    ParseState* st = (ParseState*)userData;
1022    sp<XMLNode> node = NULL;
1023    if (st->stack.size() == 0) {
1024        return;
1025    }
1026    sp<XMLNode> parent = st->stack.itemAt(st->stack.size()-1);
1027    if (parent != NULL && parent->getChildren().size() > 0) {
1028        node = parent->getChildren()[parent->getChildren().size()-1];
1029        if (node->getType() != TYPE_CDATA) {
1030            // Last node is not CDATA, need to make a new node.
1031            node = NULL;
1032        }
1033    }
1034
1035    if (node == NULL) {
1036        node = XMLNode::newCData(st->filename);
1037        node->setStartLineNumber(XML_GetCurrentLineNumber(st->parser));
1038        parent->addChild(node);
1039    }
1040
1041    node->appendChars(String16(s, len));
1042}
1043
1044void XMLCALL
1045XMLNode::endElement(void *userData, const char *name)
1046{
1047    NOISY_PARSE(printf("End Element: %s\n", name));
1048    ParseState* st = (ParseState*)userData;
1049    sp<XMLNode> node = st->stack.itemAt(st->stack.size()-1);
1050    node->setEndLineNumber(XML_GetCurrentLineNumber(st->parser));
1051    if (st->pendingComment.size() > 0) {
1052        node->appendComment(st->pendingComment);
1053        st->pendingComment = String16();
1054    }
1055    String16 ns16, name16;
1056    splitName(name, &ns16, &name16);
1057    LOG_ALWAYS_FATAL_IF(node->getElementNamespace() != ns16
1058                        || node->getElementName() != name16,
1059                        "Bad end element %s", name);
1060    st->stack.pop();
1061}
1062
1063void XMLCALL
1064XMLNode::endNamespace(void *userData, const char *prefix)
1065{
1066    const char* nonNullPrefix = prefix != NULL ? prefix : "";
1067    NOISY_PARSE(printf("End Namespace: %s\n", prefix));
1068    ParseState* st = (ParseState*)userData;
1069    sp<XMLNode> node = st->stack.itemAt(st->stack.size()-1);
1070    node->setEndLineNumber(XML_GetCurrentLineNumber(st->parser));
1071    LOG_ALWAYS_FATAL_IF(node->getNamespacePrefix() != String16(nonNullPrefix),
1072                        "Bad end namespace %s", prefix);
1073    st->stack.pop();
1074}
1075
1076void XMLCALL
1077XMLNode::commentData(void *userData, const char *comment)
1078{
1079    NOISY_PARSE(printf("Comment: %s\n", comment));
1080    ParseState* st = (ParseState*)userData;
1081    if (st->pendingComment.size() > 0) {
1082        st->pendingComment.append(String16("\n"));
1083    }
1084    st->pendingComment.append(String16(comment));
1085}
1086
1087status_t XMLNode::collect_strings(StringPool* dest, Vector<uint32_t>* outResIds,
1088        bool stripComments, bool stripRawValues) const
1089{
1090    collect_attr_strings(dest, outResIds, true);
1091
1092    int i;
1093    if (mNamespacePrefix.size() > 0) {
1094        dest->add(mNamespacePrefix, true);
1095    }
1096    if (mNamespaceUri.size() > 0) {
1097        dest->add(mNamespaceUri, true);
1098    }
1099    if (mElementName.size() > 0) {
1100        dest->add(mElementName, true);
1101    }
1102
1103    if (!stripComments && mComment.size() > 0) {
1104        dest->add(mComment, true);
1105    }
1106
1107    const int NA = mAttributes.size();
1108
1109    for (i=0; i<NA; i++) {
1110        const attribute_entry& ae = mAttributes.itemAt(i);
1111        if (ae.ns.size() > 0) {
1112            dest->add(ae.ns, true);
1113        }
1114        if (!stripRawValues || ae.needStringValue()) {
1115            dest->add(ae.string, true);
1116        }
1117        /*
1118        if (ae.value.dataType == Res_value::TYPE_NULL
1119                || ae.value.dataType == Res_value::TYPE_STRING) {
1120            dest->add(ae.string, true);
1121        }
1122        */
1123    }
1124
1125    if (mElementName.size() == 0) {
1126        // If not an element, include the CDATA, even if it is empty.
1127        dest->add(mChars, true);
1128    }
1129
1130    const int NC = mChildren.size();
1131
1132    for (i=0; i<NC; i++) {
1133        mChildren.itemAt(i)->collect_strings(dest, outResIds,
1134                stripComments, stripRawValues);
1135    }
1136
1137    return NO_ERROR;
1138}
1139
1140status_t XMLNode::collect_attr_strings(StringPool* outPool,
1141        Vector<uint32_t>* outResIds, bool allAttrs) const {
1142    const int NA = mAttributes.size();
1143
1144    for (int i=0; i<NA; i++) {
1145        const attribute_entry& attr = mAttributes.itemAt(i);
1146        uint32_t id = attr.nameResId;
1147        if (id || allAttrs) {
1148            // See if we have already assigned this resource ID to a pooled
1149            // string...
1150            const Vector<size_t>* indices = outPool->offsetsForString(attr.name);
1151            ssize_t idx = -1;
1152            if (indices != NULL) {
1153                const int NJ = indices->size();
1154                const size_t NR = outResIds->size();
1155                for (int j=0; j<NJ; j++) {
1156                    size_t strIdx = indices->itemAt(j);
1157                    if (strIdx >= NR) {
1158                        if (id == 0) {
1159                            // We don't need to assign a resource ID for this one.
1160                            idx = strIdx;
1161                            break;
1162                        }
1163                        // Just ignore strings that are out of range of
1164                        // the currently assigned resource IDs...  we add
1165                        // strings as we assign the first ID.
1166                    } else if (outResIds->itemAt(strIdx) == id) {
1167                        idx = strIdx;
1168                        break;
1169                    }
1170                }
1171            }
1172            if (idx < 0) {
1173                idx = outPool->add(attr.name);
1174                NOISY(printf("Adding attr %s (resid 0x%08x) to pool: idx=%d\n",
1175                        String8(attr.name).string(), id, idx));
1176                if (id != 0) {
1177                    while ((ssize_t)outResIds->size() <= idx) {
1178                        outResIds->add(0);
1179                    }
1180                    outResIds->replaceAt(id, idx);
1181                }
1182            }
1183            attr.namePoolIdx = idx;
1184            NOISY(printf("String %s offset=0x%08x\n",
1185                         String8(attr.name).string(), idx));
1186        }
1187    }
1188
1189    return NO_ERROR;
1190}
1191
1192status_t XMLNode::collect_resid_strings(StringPool* outPool,
1193        Vector<uint32_t>* outResIds) const
1194{
1195    collect_attr_strings(outPool, outResIds, false);
1196
1197    const int NC = mChildren.size();
1198
1199    for (int i=0; i<NC; i++) {
1200        mChildren.itemAt(i)->collect_resid_strings(outPool, outResIds);
1201    }
1202
1203    return NO_ERROR;
1204}
1205
1206status_t XMLNode::flatten_node(const StringPool& strings, const sp<AaptFile>& dest,
1207        bool stripComments, bool stripRawValues) const
1208{
1209    ResXMLTree_node node;
1210    ResXMLTree_cdataExt cdataExt;
1211    ResXMLTree_namespaceExt namespaceExt;
1212    ResXMLTree_attrExt attrExt;
1213    const void* extData = NULL;
1214    size_t extSize = 0;
1215    ResXMLTree_attribute attr;
1216
1217    const size_t NA = mAttributes.size();
1218    const size_t NC = mChildren.size();
1219    size_t i;
1220
1221    LOG_ALWAYS_FATAL_IF(NA != mAttributeOrder.size(), "Attributes messed up!");
1222
1223    const String16 id16("id");
1224    const String16 class16("class");
1225    const String16 style16("style");
1226
1227    const type type = getType();
1228
1229    memset(&node, 0, sizeof(node));
1230    memset(&attr, 0, sizeof(attr));
1231    node.header.headerSize = htods(sizeof(node));
1232    node.lineNumber = htodl(getStartLineNumber());
1233    if (!stripComments) {
1234        node.comment.index = htodl(
1235            mComment.size() > 0 ? strings.offsetForString(mComment) : -1);
1236        //if (mComment.size() > 0) {
1237        //  printf("Flattening comment: %s\n", String8(mComment).string());
1238        //}
1239    } else {
1240        node.comment.index = htodl((uint32_t)-1);
1241    }
1242    if (type == TYPE_ELEMENT) {
1243        node.header.type = htods(RES_XML_START_ELEMENT_TYPE);
1244        extData = &attrExt;
1245        extSize = sizeof(attrExt);
1246        memset(&attrExt, 0, sizeof(attrExt));
1247        if (mNamespaceUri.size() > 0) {
1248            attrExt.ns.index = htodl(strings.offsetForString(mNamespaceUri));
1249        } else {
1250            attrExt.ns.index = htodl((uint32_t)-1);
1251        }
1252        attrExt.name.index = htodl(strings.offsetForString(mElementName));
1253        attrExt.attributeStart = htods(sizeof(attrExt));
1254        attrExt.attributeSize = htods(sizeof(attr));
1255        attrExt.attributeCount = htods(NA);
1256        attrExt.idIndex = htods(0);
1257        attrExt.classIndex = htods(0);
1258        attrExt.styleIndex = htods(0);
1259        for (i=0; i<NA; i++) {
1260            ssize_t idx = mAttributeOrder.valueAt(i);
1261            const attribute_entry& ae = mAttributes.itemAt(idx);
1262            if (ae.ns.size() == 0) {
1263                if (ae.name == id16) {
1264                    attrExt.idIndex = htods(i+1);
1265                } else if (ae.name == class16) {
1266                    attrExt.classIndex = htods(i+1);
1267                } else if (ae.name == style16) {
1268                    attrExt.styleIndex = htods(i+1);
1269                }
1270            }
1271        }
1272    } else if (type == TYPE_NAMESPACE) {
1273        node.header.type = htods(RES_XML_START_NAMESPACE_TYPE);
1274        extData = &namespaceExt;
1275        extSize = sizeof(namespaceExt);
1276        memset(&namespaceExt, 0, sizeof(namespaceExt));
1277        if (mNamespacePrefix.size() > 0) {
1278            namespaceExt.prefix.index = htodl(strings.offsetForString(mNamespacePrefix));
1279        } else {
1280            namespaceExt.prefix.index = htodl((uint32_t)-1);
1281        }
1282        namespaceExt.prefix.index = htodl(strings.offsetForString(mNamespacePrefix));
1283        namespaceExt.uri.index = htodl(strings.offsetForString(mNamespaceUri));
1284        LOG_ALWAYS_FATAL_IF(NA != 0, "Namespace nodes can't have attributes!");
1285    } else if (type == TYPE_CDATA) {
1286        node.header.type = htods(RES_XML_CDATA_TYPE);
1287        extData = &cdataExt;
1288        extSize = sizeof(cdataExt);
1289        memset(&cdataExt, 0, sizeof(cdataExt));
1290        cdataExt.data.index = htodl(strings.offsetForString(mChars));
1291        cdataExt.typedData.size = htods(sizeof(cdataExt.typedData));
1292        cdataExt.typedData.res0 = 0;
1293        cdataExt.typedData.dataType = mCharsValue.dataType;
1294        cdataExt.typedData.data = htodl(mCharsValue.data);
1295        LOG_ALWAYS_FATAL_IF(NA != 0, "CDATA nodes can't have attributes!");
1296    }
1297
1298    node.header.size = htodl(sizeof(node) + extSize + (sizeof(attr)*NA));
1299
1300    dest->writeData(&node, sizeof(node));
1301    if (extSize > 0) {
1302        dest->writeData(extData, extSize);
1303    }
1304
1305    for (i=0; i<NA; i++) {
1306        ssize_t idx = mAttributeOrder.valueAt(i);
1307        const attribute_entry& ae = mAttributes.itemAt(idx);
1308        if (ae.ns.size() > 0) {
1309            attr.ns.index = htodl(strings.offsetForString(ae.ns));
1310        } else {
1311            attr.ns.index = htodl((uint32_t)-1);
1312        }
1313        attr.name.index = htodl(ae.namePoolIdx);
1314
1315        if (!stripRawValues || ae.needStringValue()) {
1316            attr.rawValue.index = htodl(strings.offsetForString(ae.string));
1317        } else {
1318            attr.rawValue.index = htodl((uint32_t)-1);
1319        }
1320        attr.typedValue.size = htods(sizeof(attr.typedValue));
1321        if (ae.value.dataType == Res_value::TYPE_NULL
1322                || ae.value.dataType == Res_value::TYPE_STRING) {
1323            attr.typedValue.res0 = 0;
1324            attr.typedValue.dataType = Res_value::TYPE_STRING;
1325            attr.typedValue.data = htodl(strings.offsetForString(ae.string));
1326        } else {
1327            attr.typedValue.res0 = 0;
1328            attr.typedValue.dataType = ae.value.dataType;
1329            attr.typedValue.data = htodl(ae.value.data);
1330        }
1331        dest->writeData(&attr, sizeof(attr));
1332    }
1333
1334    for (i=0; i<NC; i++) {
1335        status_t err = mChildren.itemAt(i)->flatten_node(strings, dest,
1336                stripComments, stripRawValues);
1337        if (err != NO_ERROR) {
1338            return err;
1339        }
1340    }
1341
1342    if (type == TYPE_ELEMENT) {
1343        ResXMLTree_endElementExt endElementExt;
1344        memset(&endElementExt, 0, sizeof(endElementExt));
1345        node.header.type = htods(RES_XML_END_ELEMENT_TYPE);
1346        node.header.size = htodl(sizeof(node)+sizeof(endElementExt));
1347        node.lineNumber = htodl(getEndLineNumber());
1348        node.comment.index = htodl((uint32_t)-1);
1349        endElementExt.ns.index = attrExt.ns.index;
1350        endElementExt.name.index = attrExt.name.index;
1351        dest->writeData(&node, sizeof(node));
1352        dest->writeData(&endElementExt, sizeof(endElementExt));
1353    } else if (type == TYPE_NAMESPACE) {
1354        node.header.type = htods(RES_XML_END_NAMESPACE_TYPE);
1355        node.lineNumber = htodl(getEndLineNumber());
1356        node.comment.index = htodl((uint32_t)-1);
1357        node.header.size = htodl(sizeof(node)+extSize);
1358        dest->writeData(&node, sizeof(node));
1359        dest->writeData(extData, extSize);
1360    }
1361
1362    return NO_ERROR;
1363}
1364