Non-const XML ID lookup.
[shibboleth/cpp-xmltooling.git] / xmltooling / util / XMLHelper.cpp
1 /*
2  *  Copyright 2001-2007 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 namespace std;
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(NULL), 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 const XMLObject* XMLHelper::getXMLObjectById(const XMLObject& tree, const XMLCh* id)
90 {
91     if (XMLString::equals(id, tree.getXMLID()))
92         return &tree;
93     
94     const XMLObject* ret;
95     const list<XMLObject*>& children = tree.getOrderedChildren();
96     for (list<XMLObject*>::const_iterator i=children.begin(); i!=children.end(); ++i) {
97         if (*i) {
98             ret = getXMLObjectById(*(*i), id);
99             if (ret)
100                 return ret;
101         }
102     }
103     
104     return NULL;
105 }
106
107 XMLObject* XMLHelper::getXMLObjectById(XMLObject& tree, const XMLCh* id)
108 {
109     if (XMLString::equals(id, tree.getXMLID()))
110         return &tree;
111     
112     XMLObject* ret;
113     const list<XMLObject*>& children = tree.getOrderedChildren();
114     for (list<XMLObject*>::const_iterator i=children.begin(); i!=children.end(); ++i) {
115         if (*i) {
116             ret = getXMLObjectById(*(*i), id);
117             if (ret)
118                 return ret;
119         }
120     }
121     
122     return NULL;
123 }
124
125 QName* XMLHelper::getNodeQName(const DOMNode* domNode)
126 {
127     if (domNode)
128         return new QName(domNode->getNamespaceURI(), domNode->getLocalName(), domNode->getPrefix());
129     return NULL; 
130 }
131
132 QName* XMLHelper::getAttributeValueAsQName(const DOMAttr* attribute)
133 {
134     if (!attribute)
135         return NULL;
136     
137     int i;
138     const XMLCh* attributeValue=attribute->getTextContent();
139     if (attributeValue && (i=XMLString::indexOf(attributeValue,chColon))>0) {
140         XMLCh* prefix=new XMLCh[i+1];
141         XMLString::subString(prefix,attributeValue,0,i);
142         prefix[i]=chNull;
143         QName* ret=new QName(attribute->lookupNamespaceURI(prefix), attributeValue + i + 1, prefix);
144         delete[] prefix;
145         return ret;
146     }
147     
148     return new QName(attribute->lookupNamespaceURI(NULL), attributeValue);
149 }
150
151 DOMElement* XMLHelper::appendChildElement(DOMElement* parentElement, DOMElement* childElement)
152 {
153     DOMDocument* parentDocument = parentElement->getOwnerDocument();
154     if (childElement->getOwnerDocument() != parentDocument) {
155         childElement = static_cast<DOMElement*>(parentDocument->importNode(childElement, true));
156     }
157
158     parentElement->appendChild(childElement);
159     return childElement;
160 }
161
162 const XMLCh* XMLHelper::getTextContent(const DOMElement* e)
163 {
164     DOMNode* child=e->getFirstChild();
165     while (child) {
166         if (child->getNodeType()==DOMNode::TEXT_NODE)
167             return child->getNodeValue();
168         child=child->getNextSibling();
169     }
170     return NULL;
171 }
172
173 DOMElement* XMLHelper::getFirstChildElement(const DOMNode* n, const XMLCh* localName)
174 {
175     DOMNode* child = n->getFirstChild();
176     while (child && child->getNodeType() != DOMNode::ELEMENT_NODE)
177         child = child->getNextSibling();
178     if (child && localName) {
179         if (!XMLString::equals(localName,child->getLocalName()))
180             return getNextSiblingElement(child, localName);
181     }
182     return static_cast<DOMElement*>(child);
183 }    
184
185 DOMElement* XMLHelper::getLastChildElement(const DOMNode* n, const XMLCh* localName)
186 {
187     DOMNode* child = n->getLastChild();
188     while (child && child->getNodeType() != DOMNode::ELEMENT_NODE)
189         child = child->getPreviousSibling();
190     if (child && localName) {
191         if (!XMLString::equals(localName,child->getLocalName()))
192             return getPreviousSiblingElement(child, localName);
193     }
194     return static_cast<DOMElement*>(child);
195 }    
196
197 DOMElement* XMLHelper::getFirstChildElement(const DOMNode* n, const XMLCh* ns, const XMLCh* localName)
198 {
199     DOMElement* e = getFirstChildElement(n, localName);
200     while (e && !XMLString::equals(e->getNamespaceURI(),ns))
201         e = getNextSiblingElement(e, localName);
202     return e;
203 }
204
205 DOMElement* XMLHelper::getLastChildElement(const DOMNode* n, const XMLCh* ns, const XMLCh* localName)
206 {
207     DOMElement* e = getLastChildElement(n, localName);
208     while (e && !XMLString::equals(e->getNamespaceURI(),ns))
209         e = getPreviousSiblingElement(e, localName);
210     return e;
211 }
212
213 DOMElement* XMLHelper::getNextSiblingElement(const DOMNode* n, const XMLCh* localName)
214 {
215     DOMNode* sib = n->getNextSibling();
216     while (sib && sib->getNodeType() != DOMNode::ELEMENT_NODE)
217         sib = sib->getNextSibling();
218     if (sib && localName) {
219         if (!XMLString::equals(localName,sib->getLocalName()))
220             return getNextSiblingElement(sib, localName);
221     }   
222     return static_cast<DOMElement*>(sib);
223 }
224
225 DOMElement* XMLHelper::getPreviousSiblingElement(const DOMNode* n, const XMLCh* localName)
226 {
227     DOMNode* sib = n->getPreviousSibling();
228     while (sib && sib->getNodeType() != DOMNode::ELEMENT_NODE)
229         sib = sib->getPreviousSibling();
230     if (sib && localName) {
231         if (!XMLString::equals(localName,sib->getLocalName()))
232             return getPreviousSiblingElement(sib, localName);
233     }   
234     return static_cast<DOMElement*>(sib);
235 }
236
237 DOMElement* XMLHelper::getNextSiblingElement(const DOMNode* n, const XMLCh* ns, const XMLCh* localName)
238 {
239     DOMElement* e = getNextSiblingElement(n, localName);
240     while (e && !XMLString::equals(e->getNamespaceURI(),ns))
241         e = getNextSiblingElement(e, localName);
242     return e;
243 }
244
245 DOMElement* XMLHelper::getPreviousSiblingElement(const DOMNode* n, const XMLCh* ns, const XMLCh* localName)
246 {
247     DOMElement* e = getPreviousSiblingElement(n, localName);
248     while (e && !XMLString::equals(e->getNamespaceURI(),ns))
249         e = getPreviousSiblingElement(e, localName);
250     return e;
251 }
252
253 void XMLHelper::serialize(const DOMNode* n, std::string& buf, bool pretty)
254 {
255     static const XMLCh impltype[] = { chLatin_L, chLatin_S, chNull };
256     static const XMLCh UTF8[]={ chLatin_U, chLatin_T, chLatin_F, chDigit_8, chNull };
257     DOMImplementation* impl=DOMImplementationRegistry::getDOMImplementation(impltype);
258     DOMWriter* serializer=(static_cast<DOMImplementationLS*>(impl))->createDOMWriter();
259     XercesJanitor<DOMWriter> janitor(serializer);
260     serializer->setEncoding(UTF8);
261     if (pretty && serializer->canSetFeature(XMLUni::fgDOMWRTFormatPrettyPrint, pretty))
262         serializer->setFeature(XMLUni::fgDOMWRTFormatPrettyPrint, pretty);
263     MemBufFormatTarget target;
264     if (!serializer->writeNode(&target,*n))
265         throw XMLParserException("unable to serialize XML");
266     buf.erase();
267     buf.append(reinterpret_cast<const char*>(target.getRawBuffer()),target.getLen());
268 }
269
270 namespace {
271     class StreamFormatTarget : public XMLFormatTarget
272     {
273     public:
274         StreamFormatTarget(std::ostream& out) : m_out(out) {}
275         ~StreamFormatTarget() {}
276
277         void writeChars(const XMLByte *const toWrite, const unsigned int count, XMLFormatter *const formatter) {
278             m_out.write(reinterpret_cast<const char*>(toWrite),count);
279         }
280
281         void flush() {
282             m_out.flush();
283         }
284
285     private:
286         std::ostream& m_out;
287     };
288 };
289
290 ostream& XMLHelper::serialize(const DOMNode* n, ostream& out, bool pretty)
291 {
292     static const XMLCh impltype[] = { chLatin_L, chLatin_S, chNull };
293     static const XMLCh UTF8[]={ chLatin_U, chLatin_T, chLatin_F, chDigit_8, chNull };
294     DOMImplementation* impl=DOMImplementationRegistry::getDOMImplementation(impltype);
295     DOMWriter* serializer=(static_cast<DOMImplementationLS*>(impl))->createDOMWriter();
296     XercesJanitor<DOMWriter> janitor(serializer);
297     serializer->setEncoding(UTF8);
298     if (pretty && serializer->canSetFeature(XMLUni::fgDOMWRTFormatPrettyPrint, pretty))
299         serializer->setFeature(XMLUni::fgDOMWRTFormatPrettyPrint, pretty);
300     StreamFormatTarget target(out);
301     if (!serializer->writeNode(&target,*n))
302         throw XMLParserException("unable to serialize XML");
303     return out;
304 }
305
306 ostream& xmltooling::operator<<(ostream& ostr, const DOMNode& node)
307 {
308     return XMLHelper::serialize(&node, ostr);
309 }
310
311 ostream& xmltooling::operator<<(ostream& ostr, const XMLObject& obj)
312 {
313     return ostr << *(obj.marshall());
314 }