aboutsummaryrefslogtreecommitdiffstats
path: root/library/cpp/xml/document/xml-document.cpp
blob: 527386f12ba80abe64016fd7fdc0d123a0240e12 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
#include "xml-document.h"

#include <libxml/xinclude.h>
#include <libxml/xpathInternals.h>

#include <library/cpp/xml/init/init.h> 

#include <util/generic/yexception.h>
#include <util/folder/dirut.h>

namespace {
    struct TInit {
        inline TInit() {
            NXml::InitEngine();
        }
    } initer;
}

namespace NXml {
    TDocument::TDocument(const TString& xml, Source type) {
        switch (type) {
            case File:
                ParseFile(xml);
                break;
            case String:
                ParseString(xml);
                break;
            case RootName: {
                TDocHolder doc(xmlNewDoc(XMLCHAR("1.0")));
                if (!doc)
                    THROW(XmlException, "Can't create xml document.");
                doc->encoding = xmlStrdup(XMLCHAR("utf-8"));

                TNodePtr node(xmlNewNode(nullptr, XMLCHAR(xml.c_str())));
                if (!node)
                    THROW(XmlException, "Can't create root node.");
                xmlDocSetRootElement(doc.Get(), node.Get());
                Y_UNUSED(node.Release());
                Doc = std::move(doc);
            } break;
            default:
                THROW(InvalidArgument, "Wrong source type");
        }
    }

    TDocument::TDocument(TDocument&& doc)
        : Doc(std::move(doc.Doc))
    {
    }

    TDocument& TDocument::operator=(TDocument&& doc) {
        if (this != &doc)
            doc.Swap(*this);

        return *this;
    }

    void TDocument::ParseFile(const TString& file) {
        if (!NFs::Exists(file))
            THROW(XmlException, "File " << file << " doesn't exist");

        TParserCtxtPtr pctx(xmlNewParserCtxt());
        if (!pctx)
            THROW(XmlException, "Can't create parser context");

        TDocHolder doc(xmlCtxtReadFile(pctx.Get(), file.c_str(), nullptr, XML_PARSE_NOCDATA));
        if (!doc)
            THROW(XmlException, "Can't parse file " << file);

        int res = xmlXIncludeProcessFlags(doc.Get(), XML_PARSE_XINCLUDE | XML_PARSE_NOCDATA | XML_PARSE_NOXINCNODE);

        if (res == -1)
            THROW(XmlException, "XIncludes processing failed");

        Doc = std::move(doc);
    }

    void TDocument::ParseString(TZtStringBuf xml) {
        TParserCtxtPtr pctx(xmlNewParserCtxt());
        if (pctx.Get() == nullptr)
            THROW(XmlException, "Can't create parser context");

        TDocHolder doc(xmlCtxtReadMemory(pctx.Get(), xml.c_str(), (int)xml.size(), nullptr, nullptr, XML_PARSE_NOCDATA));

        if (!doc)
            THROW(XmlException, "Can't parse string");

        Doc = std::move(doc);
    }

    TNode TDocument::Root() {
        xmlNode* r = xmlDocGetRootElement(Doc.Get());
        if (r == nullptr)
            THROW(XmlException, "TDocument hasn't root element");

        return TNode(Doc.Get(), r);
    }

    TConstNode TDocument::Root() const {
        xmlNode* r = xmlDocGetRootElement(Doc.Get());
        if (r == nullptr)
            THROW(XmlException, "TDocument hasn't root element");

        return TConstNode(TNode(Doc.Get(), r));
    }

    bool TNode::IsNull() const {
        return NodePointer == nullptr;
    }

    bool TNode::IsElementNode() const {
        return !IsNull() && (NodePointer->type == XML_ELEMENT_NODE);
    }

    TXPathContextPtr TNode::CreateXPathContext(const TNamespacesForXPath& nss) const {
        TXPathContextPtr ctx = xmlXPathNewContext(DocPointer);
        if (!ctx)
            THROW(XmlException, "Can't create empty xpath context");

        for (const auto& ns : nss) {
            const int r = xmlXPathRegisterNs(ctx.Get(), XMLCHAR(ns.Prefix.c_str()), XMLCHAR(ns.Url.c_str()));
            if (r != 0)
                THROW(XmlException, "Can't register namespace " << ns.Url << " with prefix " << ns.Prefix);
        }

        return ctx;
    }

    TConstNodes TNode::XPath(TZtStringBuf xpath, bool quiet, const TNamespacesForXPath& ns) const {
        TXPathContextPtr ctxt = CreateXPathContext(ns);
        return XPath(xpath, quiet, *ctxt);
    }

    TConstNodes TNode::XPath(TZtStringBuf xpath, bool quiet, TXPathContext& ctxt) const {
        if (xmlXPathSetContextNode(NodePointer, &ctxt) != 0)
            THROW(XmlException, "Can't set xpath context node, probably the context is associated with another document");

        TXPathObjectPtr obj = xmlXPathEvalExpression(XMLCHAR(xpath.c_str()), &ctxt);
        if (!obj)
            THROW(XmlException, "Can't evaluate xpath expression " << xpath);

        TConstNodes nodes(DocPointer, obj);

        if (nodes.Size() == 0 && !quiet)
            THROW(NodeNotFound, xpath);

        return nodes;
    }

    TConstNodes TNode::Nodes(TZtStringBuf xpath, bool quiet, const TNamespacesForXPath& ns) const {
        TXPathContextPtr ctxt = CreateXPathContext(ns);
        return Nodes(xpath, quiet, *ctxt);
    }

    TConstNodes TNode::Nodes(TZtStringBuf xpath, bool quiet, TXPathContext& ctxt) const {
        TConstNodes nodes = XPath(xpath, quiet, ctxt);
        if (nodes.Size() != 0 && !nodes[0].IsElementNode())
            THROW(XmlException, "xpath points to non-element nodes: " << xpath);
        return nodes;
    }

    TNode TNode::Node(TZtStringBuf xpath, bool quiet, const TNamespacesForXPath& ns) {
        TXPathContextPtr ctxt = CreateXPathContext(ns);
        return Node(xpath, quiet, *ctxt);
    }

    TConstNode TNode::Node(TZtStringBuf xpath, bool quiet, const TNamespacesForXPath& ns) const {
        TXPathContextPtr ctxt = CreateXPathContext(ns);
        return Node(xpath, quiet, *ctxt);
    }

    TNode TNode::Node(TZtStringBuf xpath, bool quiet, TXPathContext& ctxt) {
        TConstNodes n = Nodes(xpath, quiet, ctxt);

        if (n.Size() == 0 && !quiet)
            THROW(NodeNotFound, xpath);

        if (n.Size() == 0)
            return TNode();
        else
            return n[0].ConstCast();
    }

    TConstNode TNode::Node(TZtStringBuf xpath, bool quiet, TXPathContext& ctxt) const {
        return const_cast<TNode*>(this)->Node(xpath, quiet, ctxt);
    }

    TNode TNode::FirstChild(TZtStringBuf name) {
        if (IsNull())
            THROW(XmlException, "Node is null");

        return Find(NodePointer->children, name);
    }

    TConstNode TNode::FirstChild(TZtStringBuf name) const {
        return const_cast<TNode*>(this)->FirstChild(name);
    }

    TNode TNode::FirstChild() {
        if (IsNull())
            THROW(XmlException, "Node is null");

        return TNode(DocPointer, NodePointer->children);
    }

    TConstNode TNode::FirstChild() const {
        return const_cast<TNode*>(this)->FirstChild();
    }

    TNode TNode::Parent() {
        if (nullptr == NodePointer->parent)
            THROW(XmlException, "Parent node not exists");

        return TNode(DocPointer, NodePointer->parent);
    }

    TConstNode TNode::Parent() const {
        return const_cast<TNode*>(this)->Parent();
    }

    TNode TNode::NextSibling(TZtStringBuf name) {
        if (IsNull())
            THROW(XmlException, "Node is null");

        return Find(NodePointer->next, name);
    }

    TConstNode TNode::NextSibling(TZtStringBuf name) const {
        return const_cast<TNode*>(this)->NextSibling(name);
    }

    TNode TNode::NextSibling() {
        if (IsNull())
            THROW(XmlException, "Node is null");

        return TNode(DocPointer, NodePointer->next);
    }

    TConstNode TNode::NextSibling() const {
        return const_cast<TNode*>(this)->NextSibling();
    }

    /* NOTE: by default child will inherit it's parent ns */

    TNode TNode::AddChild(TZtStringBuf name) {
        return AddChild(name, "");
    }

    /* NOTE: source node will be copied, as otherwise it will be double-freed from this and its own document */

    TNode TNode::AddChild(const TConstNode& node) {
        xmlNodePtr copy = xmlDocCopyNode(node.ConstCast().NodePointer, DocPointer, 1 /* recursive */);
        copy = xmlAddChild(NodePointer, copy);
        return TNode(DocPointer, copy);
    }

    void TNode::SetPrivate(void* priv) {
        NodePointer->_private = priv;
    }

    void* TNode::GetPrivate() const {
        return NodePointer->_private;
    }

    TNode TNode::Find(xmlNode* start, TZtStringBuf name) {
        for (; start; start = start->next)
            if (start->type == XML_ELEMENT_NODE && (name.empty() || !xmlStrcmp(start->name, XMLCHAR(name.c_str()))))
                return TNode(DocPointer, start);

        return TNode();
    }

    TString TNode::Name() const {
        if (IsNull())
            THROW(XmlException, "Node is null");

        return CAST2CHAR(NodePointer->name);
    }

    TString TNode::Path() const {
        TCharPtr path(xmlGetNodePath(NodePointer));
        if (!!path)
            return CAST2CHAR(path.Get());
        else
            return "";
    }

    xmlNode* TNode::GetPtr() {
        return NodePointer;
    }

    const xmlNode* TNode::GetPtr() const {
        return NodePointer;
    }

    bool TNode::IsText() const {
        if (IsNull())
            THROW(XmlException, "Node is null");

        return NodePointer->type == XML_TEXT_NODE;
    }

    void TNode::Remove() {
        xmlNode* nodePtr = GetPtr();
        xmlUnlinkNode(nodePtr);
        xmlFreeNode(nodePtr);
    }

    static int XmlWriteToOstream(void* context, const char* buffer, int len) {
        // possibly use to save doc as well
        IOutputStream* out = (IOutputStream*)context;
        out->Write(buffer, len);
        return len;
    }

    void TNode::SaveInternal(IOutputStream& stream, TZtStringBuf enc, int options) const {
        const char* encoding = enc.size() ? enc.data() : "utf-8";
        TSaveCtxtPtr ctx(xmlSaveToIO(XmlWriteToOstream, /* close */ nullptr, &stream,
                                     encoding, options));
        if (xmlSaveTree(ctx.Get(), (xmlNode*)GetPtr()) < 0)
            THROW(XmlException, "Failed saving node to stream");
    }

    void TNode::Save(IOutputStream& stream, TZtStringBuf enc, bool shouldFormat) const {
        SaveInternal(stream, enc, shouldFormat ? XML_SAVE_FORMAT : 0);
    }

    void TNode::SaveAsHtml(IOutputStream& stream, TZtStringBuf enc, bool shouldFormat) const {
        int options = XML_SAVE_AS_HTML;
        options |= shouldFormat ? XML_SAVE_FORMAT : 0;
        SaveInternal(stream, enc, options);
    }

    TConstNodes::TConstNodes(const TConstNodes& nodes)
        : SizeValue(nodes.Size())
        , Doc(nodes.Doc)
        , Obj(nodes.Obj)
    {
    }

    TConstNodes& TConstNodes::operator=(const TConstNodes& nodes) {
        if (this != &nodes) {
            SizeValue = nodes.Size();
            Doc = nodes.Doc;
            Obj = nodes.Obj;
        }

        return *this;
    }

    TConstNodes::TConstNodes(TConstNodesRef ref)
        : SizeValue(ref.r_.Size())
        , Doc(ref.r_.Doc)
        , Obj(ref.r_.Obj)
    {
    }

    TConstNodes& TConstNodes::operator=(TConstNodesRef ref) {
        if (this != &ref.r_) {
            SizeValue = ref.r_.Size();
            Doc = ref.r_.Doc;
            Obj = ref.r_.Obj;
        }
        return *this;
    }

    TConstNodes::operator TConstNodesRef() {
        return TConstNodesRef(*this);
    }

    TConstNodes::TConstNodes(xmlDoc* doc, TXPathObjectPtr obj)
        : SizeValue(obj && obj->nodesetval ? obj->nodesetval->nodeNr : 0)
        , Doc(doc)
        , Obj(obj)
    {
    }

    TConstNode TConstNodes::operator[](size_t number) const {
        if (number + 1 > Size())
            THROW(XmlException, "index out of range " << number);

        if (!Obj || !Obj->nodesetval)
            THROW(XmlException, "Broken TConstNodes object, Obj is null");

        xmlNode* node = Obj->nodesetval->nodeTab[number];
        return TNode(Doc, node);
    }

    TConstNode TConstNodes::TNodeIter::operator*() const {
        return Nodes[Index];
    }

}