2 * Licensed to the University Corporation for Advanced Internet
3 * Development, Inc. (UCAID) under one or more contributor license
4 * agreements. See the NOTICE file distributed with this work for
5 * additional information regarding copyright ownership.
7 * UCAID licenses this file to you under the Apache License,
8 * Version 2.0 (the "License"); you may not use this file except
9 * in compliance with the License. You may obtain a copy of the
12 * http://www.apache.org/licenses/LICENSE-2.0
14 * Unless required by applicable law or agreed to in writing,
15 * software distributed under the License is distributed on an
16 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
17 * either express or implied. See the License for the specific
18 * language governing permissions and limitations under the License.
24 * A helper class for working with W3C DOM objects.
28 #include "exceptions.h"
30 #include "XMLObject.h"
31 #include "util/XMLHelper.h"
32 #include "util/XMLConstants.h"
34 #include <boost/lambda/bind.hpp>
35 #include <boost/lambda/if.hpp>
36 #include <boost/lambda/lambda.hpp>
37 #include <xercesc/framework/MemBufFormatTarget.hpp>
38 #include <xercesc/util/XMLUniDefs.hpp>
40 using namespace xmltooling;
41 using namespace xercesc;
42 using namespace boost::lambda;
43 using namespace boost;
46 static const XMLCh type[]={chLatin_t, chLatin_y, chLatin_p, chLatin_e, chNull };
48 bool XMLHelper::hasXSIType(const DOMElement* e)
50 return (e && e->hasAttributeNS(xmlconstants::XSI_NS, type));
53 xmltooling::QName* XMLHelper::getXSIType(const DOMElement* e)
55 DOMAttr* attribute = e->getAttributeNodeNS(xmlconstants::XSI_NS, type);
57 const XMLCh* attributeValue = attribute->getTextContent();
58 if (attributeValue && *attributeValue) {
60 if ((i=XMLString::indexOf(attributeValue,chColon))>0) {
61 XMLCh* prefix=new XMLCh[i+1];
62 XMLString::subString(prefix,attributeValue,0,i);
64 xmltooling::QName* ret=new xmltooling::QName(e->lookupNamespaceURI(prefix), attributeValue + i + 1, prefix);
69 return new xmltooling::QName(e->lookupNamespaceURI(nullptr), attributeValue);
77 DOMAttr* XMLHelper::getIdAttribute(const DOMElement* domElement)
79 if(!domElement->hasAttributes()) {
83 DOMNamedNodeMap* attributes = domElement->getAttributes();
85 for(XMLSize_t i = 0; i < attributes->getLength(); ++i) {
86 attribute = static_cast<DOMAttr*>(attributes->item(i));
87 if(attribute->isId()) {
95 const XMLObject* XMLHelper::getXMLObjectById(const XMLObject& tree, const XMLCh* id)
97 if (XMLString::equals(id, tree.getXMLID()))
100 const XMLObject* ret;
101 const list<XMLObject*>& children = tree.getOrderedChildren();
102 for (list<XMLObject*>::const_iterator i = children.begin(); i != children.end(); ++i) {
104 ret = getXMLObjectById(*(*i), id);
113 XMLObject* XMLHelper::getXMLObjectById(XMLObject& tree, const XMLCh* id)
115 if (XMLString::equals(id, tree.getXMLID()))
119 const list<XMLObject*>& children = tree.getOrderedChildren();
120 for (list<XMLObject*>::const_iterator i = children.begin(); i != children.end(); ++i) {
122 ret = getXMLObjectById(*(*i), id);
131 void XMLHelper::getNonVisiblyUsedPrefixes(const XMLObject& tree, map<xstring,xstring>& prefixes)
133 map<xstring,xstring> child_prefixes;
134 for(list<XMLObject*>::const_iterator i = tree.getOrderedChildren().begin(); i != tree.getOrderedChildren().end(); ++i) {
136 getNonVisiblyUsedPrefixes(*(*i), child_prefixes);
139 const set<Namespace>& nsset = tree.getNamespaces();
140 for (set<Namespace>::const_iterator ns = nsset.begin(); ns != nsset.end(); ++ns) {
141 // Check for xmlns:xml.
142 if (XMLString::equals(ns->getNamespacePrefix(), xmlconstants::XML_PREFIX) && XMLString::equals(ns->getNamespaceURI(), xmlconstants::XML_NS))
144 switch (ns->usage()) {
145 case Namespace::Indeterminate:
147 case Namespace::VisiblyUsed:
149 // See if the prefix was noted as non-visible below.
150 const XMLCh* p = ns->getNamespacePrefix() ? ns->getNamespacePrefix() : &chNull;
151 map<xstring,xstring>::iterator decl = child_prefixes.find(p);
152 if (decl != child_prefixes.end()) {
153 // It's declared below, see if it's the same namespace. If so, pull it from the set,
154 // otherwise leave it in the set.
155 if (decl->second == (ns->getNamespaceURI() ? ns->getNamespaceURI() : &chNull))
156 child_prefixes.erase(decl);
160 case Namespace::NonVisiblyUsed:
161 // It may already be in the map from another branch of the tree, but as long
162 // as it's set to something so the parent knows about it, we're good.
163 prefixes[ns->getNamespacePrefix() ? ns->getNamespacePrefix() : &chNull] = (ns->getNamespaceURI() ? ns->getNamespaceURI() : &chNull);
168 prefixes.insert(child_prefixes.begin(), child_prefixes.end());
171 xmltooling::QName* XMLHelper::getNodeQName(const DOMNode* domNode)
174 return new xmltooling::QName(domNode->getNamespaceURI(), domNode->getLocalName(), domNode->getPrefix());
178 xmltooling::QName* XMLHelper::getAttributeValueAsQName(const DOMAttr* attribute)
180 return getNodeValueAsQName(attribute);
183 xmltooling::QName* XMLHelper::getNodeValueAsQName(const DOMNode* domNode)
188 const XMLCh* value=domNode->getTextContent();
189 if (!value || !*value)
193 if ((i=XMLString::indexOf(value,chColon))>0) {
194 XMLCh* prefix=new XMLCh[i+1];
195 XMLString::subString(prefix,value,0,i);
197 xmltooling::QName* ret=new xmltooling::QName(domNode->lookupNamespaceURI(prefix), value + i + 1, prefix);
202 return new xmltooling::QName(domNode->lookupNamespaceURI(nullptr), value);
205 bool XMLHelper::getNodeValueAsBool(const xercesc::DOMNode* domNode, bool def)
209 const XMLCh* value = domNode->getNodeValue();
210 if (!value || !*value)
212 if (*value == chLatin_t || *value == chDigit_1)
214 else if (*value == chLatin_f || *value == chDigit_0)
219 DOMElement* XMLHelper::appendChildElement(DOMElement* parentElement, DOMElement* childElement)
221 DOMDocument* parentDocument = parentElement->getOwnerDocument();
222 if (childElement->getOwnerDocument() != parentDocument) {
223 childElement = static_cast<DOMElement*>(parentDocument->importNode(childElement, true));
226 parentElement->appendChild(childElement);
230 bool XMLHelper::isNodeNamed(const xercesc::DOMNode* n, const XMLCh* ns, const XMLCh* local)
232 return (n && XMLString::equals(local,n->getLocalName()) && XMLString::equals(ns,n->getNamespaceURI()));
235 const XMLCh* XMLHelper::getTextContent(const DOMElement* e)
237 DOMNode* child = e ? e->getFirstChild() : nullptr;
239 if (child->getNodeType() == DOMNode::TEXT_NODE)
240 return child->getNodeValue();
241 child = child->getNextSibling();
246 DOMElement* XMLHelper::getFirstChildElement(const DOMNode* n, const XMLCh* localName)
248 DOMNode* child = n ? n->getFirstChild() : nullptr;
249 while (child && child->getNodeType() != DOMNode::ELEMENT_NODE)
250 child = child->getNextSibling();
251 if (child && localName) {
252 if (!XMLString::equals(localName,child->getLocalName()))
253 return getNextSiblingElement(child, localName);
255 return static_cast<DOMElement*>(child);
258 DOMElement* XMLHelper::getLastChildElement(const DOMNode* n, const XMLCh* localName)
260 DOMNode* child = n ? n->getLastChild() : nullptr;
261 while (child && child->getNodeType() != DOMNode::ELEMENT_NODE)
262 child = child->getPreviousSibling();
263 if (child && localName) {
264 if (!XMLString::equals(localName,child->getLocalName()))
265 return getPreviousSiblingElement(child, localName);
267 return static_cast<DOMElement*>(child);
270 DOMElement* XMLHelper::getFirstChildElement(const DOMNode* n, const XMLCh* ns, const XMLCh* localName)
272 DOMElement* e = getFirstChildElement(n, localName);
273 while (e && !XMLString::equals(e->getNamespaceURI(),ns))
274 e = getNextSiblingElement(e, localName);
278 DOMElement* XMLHelper::getLastChildElement(const DOMNode* n, const XMLCh* ns, const XMLCh* localName)
280 DOMElement* e = getLastChildElement(n, localName);
281 while (e && !XMLString::equals(e->getNamespaceURI(),ns))
282 e = getPreviousSiblingElement(e, localName);
286 DOMElement* XMLHelper::getNextSiblingElement(const DOMNode* n, const XMLCh* localName)
288 DOMNode* sib = n ? n->getNextSibling() : nullptr;
289 while (sib && sib->getNodeType() != DOMNode::ELEMENT_NODE)
290 sib = sib->getNextSibling();
291 if (sib && localName) {
292 if (!XMLString::equals(localName,sib->getLocalName()))
293 return getNextSiblingElement(sib, localName);
295 return static_cast<DOMElement*>(sib);
298 DOMElement* XMLHelper::getPreviousSiblingElement(const DOMNode* n, const XMLCh* localName)
300 DOMNode* sib = n ? n->getPreviousSibling() : nullptr;
301 while (sib && sib->getNodeType() != DOMNode::ELEMENT_NODE)
302 sib = sib->getPreviousSibling();
303 if (sib && localName) {
304 if (!XMLString::equals(localName,sib->getLocalName()))
305 return getPreviousSiblingElement(sib, localName);
307 return static_cast<DOMElement*>(sib);
310 DOMElement* XMLHelper::getNextSiblingElement(const DOMNode* n, const XMLCh* ns, const XMLCh* localName)
312 DOMElement* e = getNextSiblingElement(n, localName);
313 while (e && !XMLString::equals(e->getNamespaceURI(),ns))
314 e = getNextSiblingElement(e, localName);
318 DOMElement* XMLHelper::getPreviousSiblingElement(const DOMNode* n, const XMLCh* ns, const XMLCh* localName)
320 DOMElement* e = getPreviousSiblingElement(n, localName);
321 while (e && !XMLString::equals(e->getNamespaceURI(),ns))
322 e = getPreviousSiblingElement(e, localName);
326 string XMLHelper::getAttrString(const DOMElement* e, const char* defValue, const XMLCh* localName, const XMLCh* ns)
329 auto_ptr_char val(e->getAttributeNS(ns, localName));
330 if (val.get() && *val.get())
333 return defValue ? defValue : "";
336 int XMLHelper::getAttrInt(const DOMElement* e, int defValue, const XMLCh* localName, const XMLCh* ns)
339 const XMLCh* val = e->getAttributeNS(ns, localName);
341 int i = XMLString::parseInt(val);
349 bool XMLHelper::getAttrBool(const DOMElement* e, bool defValue, const XMLCh* localName, const XMLCh* ns)
352 const XMLCh* val = e->getAttributeNS(ns, localName);
354 if (*val == chLatin_t || *val == chDigit_1)
356 if (*val == chLatin_f || *val == chDigit_0)
363 void XMLHelper::serialize(const DOMNode* n, std::string& buf, bool pretty)
365 static const XMLCh impltype[] = { chLatin_L, chLatin_S, chNull };
366 static const XMLCh UTF8[]={ chLatin_U, chLatin_T, chLatin_F, chDash, chDigit_8, chNull };
368 MemBufFormatTarget target;
369 DOMImplementation* impl=DOMImplementationRegistry::getDOMImplementation(impltype);
371 #ifdef XMLTOOLING_XERCESC_COMPLIANT_DOMLS
372 DOMLSSerializer* serializer = static_cast<DOMImplementationLS*>(impl)->createLSSerializer();
373 XercesJanitor<DOMLSSerializer> janitor(serializer);
374 if (pretty && serializer->getDomConfig()->canSetParameter(XMLUni::fgDOMWRTFormatPrettyPrint, pretty))
375 serializer->getDomConfig()->setParameter(XMLUni::fgDOMWRTFormatPrettyPrint, pretty);
376 DOMLSOutput *theOutput = static_cast<DOMImplementationLS*>(impl)->createLSOutput();
377 XercesJanitor<DOMLSOutput> j_theOutput(theOutput);
378 theOutput->setEncoding(UTF8);
379 theOutput->setByteStream(&target);
380 if (!serializer->write(n, theOutput))
381 throw XMLParserException("unable to serialize XML");
383 DOMWriter* serializer = static_cast<DOMImplementationLS*>(impl)->createDOMWriter();
384 XercesJanitor<DOMWriter> janitor(serializer);
385 serializer->setEncoding(UTF8);
386 if (pretty && serializer->canSetFeature(XMLUni::fgDOMWRTFormatPrettyPrint, pretty))
387 serializer->setFeature(XMLUni::fgDOMWRTFormatPrettyPrint, pretty);
388 if (!serializer->writeNode(&target, *n))
389 throw XMLParserException("unable to serialize XML");
393 buf.append(reinterpret_cast<const char*>(target.getRawBuffer()),target.getLen());
397 class StreamFormatTarget : public XMLFormatTarget
400 StreamFormatTarget(std::ostream& out) : m_out(out) {}
401 ~StreamFormatTarget() {}
403 void writeChars(const XMLByte *const toWrite, const xsecsize_t count, XMLFormatter *const formatter) {
404 m_out.write(reinterpret_cast<const char*>(toWrite),count);
416 ostream& XMLHelper::serialize(const DOMNode* n, ostream& out, bool pretty)
418 static const XMLCh impltype[] = { chLatin_L, chLatin_S, chNull };
419 static const XMLCh UTF8[]={ chLatin_U, chLatin_T, chLatin_F, chDash, chDigit_8, chNull };
421 StreamFormatTarget target(out);
422 DOMImplementation* impl=DOMImplementationRegistry::getDOMImplementation(impltype);
424 #ifdef XMLTOOLING_XERCESC_COMPLIANT_DOMLS
425 DOMLSSerializer* serializer = static_cast<DOMImplementationLS*>(impl)->createLSSerializer();
426 XercesJanitor<DOMLSSerializer> janitor(serializer);
427 if (pretty && serializer->getDomConfig()->canSetParameter(XMLUni::fgDOMWRTFormatPrettyPrint, pretty))
428 serializer->getDomConfig()->setParameter(XMLUni::fgDOMWRTFormatPrettyPrint, pretty);
429 DOMLSOutput *theOutput = static_cast<DOMImplementationLS*>(impl)->createLSOutput();
430 XercesJanitor<DOMLSOutput> j_theOutput(theOutput);
431 theOutput->setEncoding(UTF8);
432 theOutput->setByteStream(&target);
433 if (!serializer->write(n, theOutput))
434 throw XMLParserException("unable to serialize XML");
436 DOMWriter* serializer=(static_cast<DOMImplementationLS*>(impl))->createDOMWriter();
437 XercesJanitor<DOMWriter> janitor(serializer);
438 serializer->setEncoding(UTF8);
439 if (pretty && serializer->canSetFeature(XMLUni::fgDOMWRTFormatPrettyPrint, pretty))
440 serializer->setFeature(XMLUni::fgDOMWRTFormatPrettyPrint, pretty);
441 if (!serializer->writeNode(&target,*n))
442 throw XMLParserException("unable to serialize XML");
448 ostream& xmltooling::operator<<(ostream& ostr, const DOMNode& node)
450 return XMLHelper::serialize(&node, ostr);
453 ostream& xmltooling::operator<<(ostream& ostr, const XMLObject& obj)
455 return ostr << *(obj.marshall());