xml抽象

#include<string>
using namespace std;
class Content
{
    public:
        string flag;
    public:
        virtual string getContent(){}
        virtual void setContent(){}
        virtual string toString1(){}
        virtual string toString2(){}
        virtual void show(){}
};


#include<cstdio>
#include<vector>
#include"Content.h"
#include"Text.h"
using namespace std;

class Element: public Content
{
    private:
        string name;
        vector<Content *> contents;
    public:
        Element(){this->flag = "Element";}
        Element(string name){this->name = name; this->flag = "Element";}
        virtual void setContent(string name) { this->name = name;}
        virtual string getContent(){ return this->name ;}
        virtual string toString1();
        virtual string toString2();
        Element* addElement(string name);
        void addText(string text);
        void show();
};
Element* Element:: addElement(string name)
{
    Element *element =  new Element(name);
    this->contents.push_back(element);
    return element;
}

void Element:: addText(string text)
{
    Text *t = new Text(text);
    this->contents.push_back(t);
}

string Element:: toString1()
{
    string str = "\n<" + this->name + ">";
    return str;
}

string Element:: toString2()
{
    string str = "</" + this->name + ">\n";
    return str;
}

void Element:: show()
{
    int len = this->contents.size();
    cout <<this->toString1();
    for(int i = 0 ; i < len ; ++ i)
    {
        if(this->contents[i]->flag == "Element" )
        {
            this->contents[i]->show();
           // cout << this->contents[i]->toString2();
        }
        else
        {
            cout << this->contents[i]->toString1();
        }
    }
    cout <<this->toString2();
    delete this;
}


#include<iostream>

using namespace std;

class Text: public Content
{
    private:
        string text;
    public :
        Text(){this->flag = "Text";}
        Text(string text){this->text = text ; this->flag = "Text";}
        virtual string getContent(){return this->text;}
        virtual void setContent(string text){this->text = text;};
        virtual string toString1();
        virtual string toString2(){}
};

string Text:: toString1()
{
    return this->text;
}

#include"Element.h"

using namespace std;

int main()
{
    Element *book = new Element("book");
    Element *title = book->addElement("title");
    title->addText("java");

    Element *des = book->addElement("describe");
    Element *author = des->addElement("author");
    Element *age = author->addElement("age");
    age->addText("22");
    Element *name = author->addElement("name");
    name->addText("wanbo");

    Element *price = book->addElement("price");
    price->addText("12.5");

    book->show();
    return 0;
}
相關文章
相關標籤/搜索