Stream operators (Unicode string operator is an experiment)
[shibboleth/cpp-xmltooling.git] / xmltooling / util / XMLHelper.cpp
1 /*
2  *  Copyright 2001-2006 Internet2
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 /**
18  * XMLHelper.cpp
19  * 
20  * A helper class for working with W3C DOM objects. 
21  */
22
23 #include "internal.h"
24 #include "exceptions.h"
25 #include "util/XMLHelper.h"
26 #include "util/XMLConstants.h"
27
28 #include <xercesc/framework/MemBufFormatTarget.hpp>
29 #include <xercesc/util/XMLUniDefs.hpp>
30
31 using namespace xmltooling;
32 using std::ostream;
33
34 static const XMLCh type[]={chLatin_t, chLatin_y, chLatin_p, chLatin_e, chNull };
35     
36 bool XMLHelper::hasXSIType(const DOMElement* e)
37 {
38     if (e) {
39         if (e->hasAttributeNS(xmlconstants::XSI_NS, type)) {
40             return true;
41         }
42     }
43
44     return false;
45 }
46
47 QName* XMLHelper::getXSIType(const DOMElement* e)
48 {
49     DOMAttr* attribute = e->getAttributeNodeNS(xmlconstants::XSI_NS, type);
50     if (attribute) {
51         const XMLCh* attributeValue = attribute->getTextContent();
52         if (attributeValue && *attributeValue) {
53             int i;
54             if ((i=XMLString::indexOf(attributeValue,chColon))>0) {
55                 XMLCh* prefix=new XMLCh[i+1];
56                 XMLString::subString(prefix,attributeValue,0,i);
57                 prefix[i]=chNull;
58                 QName* ret=new QName(e->lookupNamespaceURI(prefix), attributeValue + i + 1, prefix);
59                 delete[] prefix;
60                 return ret;
61             }
62             else {
63                 return new QName(e->lookupNamespaceURI(&chNull), attributeValue);
64             }
65         }
66     }
67
68     return NULL;
69 }
70
71 DOMAttr* XMLHelper::getIdAttribute(const DOMElement* domElement)
72 {
73     if(!domElement->hasAttributes()) {
74         return NULL;
75     }
76     
77     DOMNamedNodeMap* attributes = domElement->getAttributes();
78     DOMAttr* attribute;
79     for(XMLSize_t i = 0; i < attributes->getLength(); i++) {
80         attribute = static_cast<DOMAttr*>(attributes->item(i));
81         if(attribute->isId()) {
82             return attribute;
83         }
84     }
85     
86     return NULL;
87 }
88
89 QName* XMLHelper::getNodeQName(const DOMNode* domNode)
90 {
91     if (domNode)
92         return new QName(domNode->getNamespaceURI(), domNode->getLocalName(), domNode->getPrefix());
93     return NULL; 
94 }
95
96 QName* XMLHelper::getAttributeValueAsQName(const DOMAttr* attribute)
97 {
98     if (!attribute)
99         return NULL;
100     
101     int i;
102     const XMLCh* attributeValue=attribute->getTextContent();
103     if (attributeValue && (i=XMLString::indexOf(attributeValue,chColon))>0) {
104         XMLCh* prefix=new XMLCh[i+1];
105         XMLString::subString(prefix,attributeValue,0,i);
106         prefix[i]=chNull;
107         QName* ret=new QName(attribute->lookupNamespaceURI(prefix), attributeValue + i + 1, prefix);
108         delete[] prefix;
109         return ret;
110     }
111     
112     return new QName(attribute->lookupNamespaceURI(NULL), attributeValue);
113 }
114
115 DOMElement* XMLHelper::appendChildElement(DOMElement* parentElement, DOMElement* childElement)
116 {
117     DOMDocument* parentDocument = parentElement->getOwnerDocument();
118     if (childElement->getOwnerDocument() != parentDocument) {
119         childElement = static_cast<DOMElement*>(parentDocument->importNode(childElement, true));
120     }
121
122     parentElement->appendChild(childElement);
123     return childElement;
124 }
125
126 const XMLCh* XMLHelper::getTextContent(const DOMElement* e)
127 {
128     DOMNode* child=e->getFirstChild();
129     while (child) {
130         if (child->getNodeType()==DOMNode::TEXT_NODE)
131             return child->getNodeValue();
132         child=child->getNextSibling();
133     }
134     return NULL;
135 }
136
137 DOMElement* XMLHelper::getFirstChildElement(const DOMNode* n, const XMLCh* localName)
138 {
139     DOMNode* child = n->getFirstChild();
140     while (child && child->getNodeType() != DOMNode::ELEMENT_NODE)
141         child = child->getNextSibling();
142     if (child && localName) {
143         if (!XMLString::equals(localName,child->getLocalName()))
144             return getNextSiblingElement(child, localName);
145     }
146     return static_cast<DOMElement*>(child);
147 }    
148
149 DOMElement* XMLHelper::getLastChildElement(const DOMNode* n, const XMLCh* localName)
150 {
151     DOMNode* child = n->getLastChild();
152     while (child && child->getNodeType() != DOMNode::ELEMENT_NODE)
153         child = child->getPreviousSibling();
154     if (child && localName) {
155         if (!XMLString::equals(localName,child->getLocalName()))
156             return getPreviousSiblingElement(child, localName);
157     }
158     return static_cast<DOMElement*>(child);
159 }    
160
161 DOMElement* XMLHelper::getFirstChildElement(const DOMNode* n, const XMLCh* ns, const XMLCh* localName)
162 {
163     DOMElement* e = getFirstChildElement(n, localName);
164     while (e && !XMLString::equals(e->getNamespaceURI(),ns))
165         e = getNextSiblingElement(e, localName);
166     return e;
167 }
168
169 DOMElement* XMLHelper::getLastChildElement(const DOMNode* n, const XMLCh* ns, const XMLCh* localName)
170 {
171     DOMElement* e = getLastChildElement(n, localName);
172     while (e && !XMLString::equals(e->getNamespaceURI(),ns))
173         e = getPreviousSiblingElement(e, localName);
174     return e;
175 }
176
177 DOMElement* XMLHelper::getNextSiblingElement(const DOMNode* n, const XMLCh* localName)
178 {
179     DOMNode* sib = n->getNextSibling();
180     while (sib && sib->getNodeType() != DOMNode::ELEMENT_NODE)
181         sib = sib->getNextSibling();
182     if (sib && localName) {
183         if (!XMLString::equals(localName,sib->getLocalName()))
184             return getNextSiblingElement(sib, localName);
185     }   
186     return static_cast<DOMElement*>(sib);
187 }
188
189 DOMElement* XMLHelper::getPreviousSiblingElement(const DOMNode* n, const XMLCh* localName)
190 {
191     DOMNode* sib = n->getPreviousSibling();
192     while (sib && sib->getNodeType() != DOMNode::ELEMENT_NODE)
193         sib = sib->getPreviousSibling();
194     if (sib && localName) {
195         if (!XMLString::equals(localName,sib->getLocalName()))
196             return getPreviousSiblingElement(sib, localName);
197     }   
198     return static_cast<DOMElement*>(sib);
199 }
200
201 DOMElement* XMLHelper::getNextSiblingElement(const DOMNode* n, const XMLCh* ns, const XMLCh* localName)
202 {
203     DOMElement* e = getNextSiblingElement(n, localName);
204     while (e && !XMLString::equals(e->getNamespaceURI(),ns))
205         e = getNextSiblingElement(e, localName);
206     return e;
207 }
208
209 DOMElement* XMLHelper::getPreviousSiblingElement(const DOMNode* n, const XMLCh* ns, const XMLCh* localName)
210 {
211     DOMElement* e = getPreviousSiblingElement(n, localName);
212     while (e && !XMLString::equals(e->getNamespaceURI(),ns))
213         e = getPreviousSiblingElement(e, localName);
214     return e;
215 }
216
217 void XMLHelper::serialize(const DOMNode* n, std::string& buf)
218 {
219     static const XMLCh impltype[] = { chLatin_L, chLatin_S, chNull };
220     static const XMLCh UTF8[]={ chLatin_U, chLatin_T, chLatin_F, chDigit_8, chNull };
221     DOMImplementation* impl=DOMImplementationRegistry::getDOMImplementation(impltype);
222     DOMWriter* serializer=(static_cast<DOMImplementationLS*>(impl))->createDOMWriter();
223     XercesJanitor<DOMWriter> janitor(serializer);
224     serializer->setEncoding(UTF8);
225     MemBufFormatTarget target;
226     if (!serializer->writeNode(&target,*n))
227         throw XMLParserException("unable to serialize XML");
228     buf.erase();
229     buf.append(reinterpret_cast<const char*>(target.getRawBuffer()),target.getLen());
230 }
231
232 namespace {
233     class StreamFormatTarget : public XMLFormatTarget
234     {
235     public:
236         StreamFormatTarget(std::ostream& out) : m_out(out) {}
237         ~StreamFormatTarget() {}
238
239         void writeChars(const XMLByte *const toWrite, const unsigned int count, XMLFormatter *const formatter) {
240             m_out.write(reinterpret_cast<const char*>(toWrite),count);
241         }
242
243         void flush() {
244             m_out.flush();
245         }
246
247     private:
248         std::ostream& m_out;
249     };
250 };
251
252 void XMLHelper::serialize(const DOMNode* n, std::ostream& out)
253 {
254     static const XMLCh impltype[] = { chLatin_L, chLatin_S, chNull };
255     static const XMLCh UTF8[]={ chLatin_U, chLatin_T, chLatin_F, chDigit_8, chNull };
256     DOMImplementation* impl=DOMImplementationRegistry::getDOMImplementation(impltype);
257     DOMWriter* serializer=(static_cast<DOMImplementationLS*>(impl))->createDOMWriter();
258     XercesJanitor<DOMWriter> janitor(serializer);
259     serializer->setEncoding(UTF8);
260     StreamFormatTarget target(out);
261     if (!serializer->writeNode(&target,*n))
262         throw XMLParserException("unable to serialize XML");
263 }
264
265 ostream& xmltooling::operator<<(ostream& ostr, const DOMNode& node)
266 {
267     XMLHelper::serialize(&node, ostr);
268     return ostr;
269 }
270
271 ostream& xmltooling::operator<<(ostream& ostr, const XMLObject& obj)
272 {
273     return ostr << obj.marshall();
274 }