6f53be1e57d3d6cac85911a90a6414676eb03acc
[libi2ncommon] / xmllib / xmlcommon.cpp
1 /***************************************************************************
2                    xmlcommon.cpp - Common XML functions
3                              -------------------
4     begin                : Tue Apr 27 2004
5     copyright            : (C) 2004 by Intra2net AG
6     email                : info@intra2net.com
7  ***************************************************************************/
8
9 #include <xmlcommon.hpp>
10 #include <exception.hxx>
11 #include <sstream>
12 #include <vector>
13
14 using namespace xmlpp;
15 using namespace std;
16
17 namespace I2n {
18
19 void xml_validate_dtd(Node *root, const std::string &subsetname, const std::string &dtdname)
20 {
21     // Create empty document, set DTD
22     Document doc;
23     doc.set_internal_subset(subsetname, "", dtdname);
24     Element *newRoot = doc.create_root_node(root->get_name(), "", "");
25     
26     // Import nodes
27     Node::NodeList list = root->get_children();
28     Node::NodeList::iterator list_end = list.end();
29     for(xmlpp::Node::NodeList::iterator iter = list.begin(); iter != list_end; ++iter)
30         newRoot->import_node(*iter);
31
32     // Parse XML again to validate it
33     DomParser parser;
34     parser.set_validate();
35     parser.parse_memory(doc.write_to_string_formatted());
36 }
37
38 std::string xml_get_child_content(xmlpp::Node *base, const std::string &elementname)
39 {
40     vector<xmlpp::Node*> nodes;
41
42     // Read in value
43     nodes = base->find(elementname);
44
45     if (nodes.size() != 1)
46     {
47         ostringstream os;
48         os << "xml parse error at line " << base->get_line() << ": element ambiguous or not found: " << elementname;
49         throw EXCEPTION(runtime_error_src,os.str());
50     }
51
52     return xml_get_text_content(nodes[0], elementname);
53 }
54
55 std::string xml_get_text_content(xmlpp::Node *node, const std::string &elementname)
56 {
57     if (node->get_children().size() <= 0)
58     {
59         ostringstream os;
60         os << "xml parse error at line " << node->get_line() << ": element content not found in " << elementname;
61         throw EXCEPTION(runtime_error_src,os.str());
62     }
63
64     xmlpp::Node::NodeList childs = node->get_children();
65     xmlpp::Node::NodeList::iterator text = childs.begin();
66     const xmlpp::ContentNode *nodeText=dynamic_cast<const xmlpp::ContentNode*>(*text);
67
68     if (nodeText)
69         return nodeText->get_content();
70     else
71     {
72         ostringstream os;
73         os << "xml parse error at line " << (*text)->get_line() << ": element " << elementname << " does not contain content";
74         throw EXCEPTION(runtime_error_src,os.str());
75     }
76
77     // not reached
78     return "";
79 }
80
81 }