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;
135 tree.getOrderedChildren().begin(), tree.getOrderedChildren().end(),
136 if_(_1 != ((XMLObject*)nullptr))[lambda::bind(&getNonVisiblyUsedPrefixes, boost::ref(*_1), boost::ref(child_prefixes))]
138 const set<Namespace>& nsset = tree.getNamespaces();
139 for (set<Namespace>::const_iterator ns = nsset.begin(); ns != nsset.end(); ++ns) {
140 // Check for xmlns:xml.
141 if (XMLString::equals(ns->getNamespacePrefix(), xmlconstants::XML_PREFIX) && XMLString::equals(ns->getNamespaceURI(), xmlconstants::XML_NS))
143 switch (ns->usage()) {
144 case Namespace::Indeterminate:
146 case Namespace::VisiblyUsed:
148 // See if the prefix was noted as non-visible below.
149 const XMLCh* p = ns->getNamespacePrefix() ? ns->getNamespacePrefix() : &chNull;
150 map<xstring,xstring>::iterator decl = child_prefixes.find(p);
151 if (decl != child_prefixes.end()) {
152 // It's declared below, see if it's the same namespace. If so, pull it from the set,
153 // otherwise leave it in the set.
154 if (decl->second == (ns->getNamespaceURI() ? ns->getNamespaceURI() : &chNull))
155 child_prefixes.erase(decl);
159 case Namespace::NonVisiblyUsed:
160 // It may already be in the map from another branch of the tree, but as long
161 // as it's set to something so the parent knows about it, we're good.
162 prefixes[ns->getNamespacePrefix() ? ns->getNamespacePrefix() : &chNull] = (ns->getNamespaceURI() ? ns->getNamespaceURI() : &chNull);
167 prefixes.insert(child_prefixes.begin(), child_prefixes.end());
170 xmltooling::QName* XMLHelper::getNodeQName(const DOMNode* domNode)
173 return new xmltooling::QName(domNode->getNamespaceURI(), domNode->getLocalName(), domNode->getPrefix());
177 xmltooling::QName* XMLHelper::getAttributeValueAsQName(const DOMAttr* attribute)
179 return getNodeValueAsQName(attribute);
182 xmltooling::QName* XMLHelper::getNodeValueAsQName(const DOMNode* domNode)
187 const XMLCh* value=domNode->getTextContent();
188 if (!value || !*value)
192 if ((i=XMLString::indexOf(value,chColon))>0) {
193 XMLCh* prefix=new XMLCh[i+1];
194 XMLString::subString(prefix,value,0,i);
196 xmltooling::QName* ret=new xmltooling::QName(domNode->lookupNamespaceURI(prefix), value + i + 1, prefix);
201 return new xmltooling::QName(domNode->lookupNamespaceURI(nullptr), value);
204 bool XMLHelper::getNodeValueAsBool(const xercesc::DOMNode* domNode, bool def)
208 const XMLCh* value = domNode->getNodeValue();
209 if (!value || !*value)
211 if (*value == chLatin_t || *value == chDigit_1)
213 else if (*value == chLatin_f || *value == chDigit_0)
218 DOMElement* XMLHelper::appendChildElement(DOMElement* parentElement, DOMElement* childElement)
220 DOMDocument* parentDocument = parentElement->getOwnerDocument();
221 if (childElement->getOwnerDocument() != parentDocument) {
222 childElement = static_cast<DOMElement*>(parentDocument->importNode(childElement, true));
225 parentElement->appendChild(childElement);
229 bool XMLHelper::isNodeNamed(const xercesc::DOMNode* n, const XMLCh* ns, const XMLCh* local)
231 return (n && XMLString::equals(local,n->getLocalName()) && XMLString::equals(ns,n->getNamespaceURI()));
234 const XMLCh* XMLHelper::getTextContent(const DOMElement* e)
236 DOMNode* child = e ? e->getFirstChild() : nullptr;
238 if (child->getNodeType() == DOMNode::TEXT_NODE)
239 return child->getNodeValue();
240 child = child->getNextSibling();
245 DOMElement* XMLHelper::getFirstChildElement(const DOMNode* n, const XMLCh* localName)
247 DOMNode* child = n ? n->getFirstChild() : nullptr;
248 while (child && child->getNodeType() != DOMNode::ELEMENT_NODE)
249 child = child->getNextSibling();
250 if (child && localName) {
251 if (!XMLString::equals(localName,child->getLocalName()))
252 return getNextSiblingElement(child, localName);
254 return static_cast<DOMElement*>(child);
257 DOMElement* XMLHelper::getLastChildElement(const DOMNode* n, const XMLCh* localName)
259 DOMNode* child = n ? n->getLastChild() : nullptr;
260 while (child && child->getNodeType() != DOMNode::ELEMENT_NODE)
261 child = child->getPreviousSibling();
262 if (child && localName) {
263 if (!XMLString::equals(localName,child->getLocalName()))
264 return getPreviousSiblingElement(child, localName);
266 return static_cast<DOMElement*>(child);
269 DOMElement* XMLHelper::getFirstChildElement(const DOMNode* n, const XMLCh* ns, const XMLCh* localName)
271 DOMElement* e = getFirstChildElement(n, localName);
272 while (e && !XMLString::equals(e->getNamespaceURI(),ns))
273 e = getNextSiblingElement(e, localName);
277 DOMElement* XMLHelper::getLastChildElement(const DOMNode* n, const XMLCh* ns, const XMLCh* localName)
279 DOMElement* e = getLastChildElement(n, localName);
280 while (e && !XMLString::equals(e->getNamespaceURI(),ns))
281 e = getPreviousSiblingElement(e, localName);
285 DOMElement* XMLHelper::getNextSiblingElement(const DOMNode* n, const XMLCh* localName)
287 DOMNode* sib = n ? n->getNextSibling() : nullptr;
288 while (sib && sib->getNodeType() != DOMNode::ELEMENT_NODE)
289 sib = sib->getNextSibling();
290 if (sib && localName) {
291 if (!XMLString::equals(localName,sib->getLocalName()))
292 return getNextSiblingElement(sib, localName);
294 return static_cast<DOMElement*>(sib);
297 DOMElement* XMLHelper::getPreviousSiblingElement(const DOMNode* n, const XMLCh* localName)
299 DOMNode* sib = n ? n->getPreviousSibling() : nullptr;
300 while (sib && sib->getNodeType() != DOMNode::ELEMENT_NODE)
301 sib = sib->getPreviousSibling();
302 if (sib && localName) {
303 if (!XMLString::equals(localName,sib->getLocalName()))
304 return getPreviousSiblingElement(sib, localName);
306 return static_cast<DOMElement*>(sib);
309 DOMElement* XMLHelper::getNextSiblingElement(const DOMNode* n, const XMLCh* ns, const XMLCh* localName)
311 DOMElement* e = getNextSiblingElement(n, localName);
312 while (e && !XMLString::equals(e->getNamespaceURI(),ns))
313 e = getNextSiblingElement(e, localName);
317 DOMElement* XMLHelper::getPreviousSiblingElement(const DOMNode* n, const XMLCh* ns, const XMLCh* localName)
319 DOMElement* e = getPreviousSiblingElement(n, localName);
320 while (e && !XMLString::equals(e->getNamespaceURI(),ns))
321 e = getPreviousSiblingElement(e, localName);
325 string XMLHelper::getAttrString(const DOMElement* e, const char* defValue, const XMLCh* localName, const XMLCh* ns)
328 auto_ptr_char val(e->getAttributeNS(ns, localName));
329 if (val.get() && *val.get())
332 return defValue ? defValue : "";
335 int XMLHelper::getAttrInt(const DOMElement* e, int defValue, const XMLCh* localName, const XMLCh* ns)
338 const XMLCh* val = e->getAttributeNS(ns, localName);
340 int i = XMLString::parseInt(val);
348 bool XMLHelper::getAttrBool(const DOMElement* e, bool defValue, const XMLCh* localName, const XMLCh* ns)
351 const XMLCh* val = e->getAttributeNS(ns, localName);
353 if (*val == chLatin_t || *val == chDigit_1)
355 if (*val == chLatin_f || *val == chDigit_0)
362 void XMLHelper::serialize(const DOMNode* n, std::string& buf, bool pretty)
364 static const XMLCh impltype[] = { chLatin_L, chLatin_S, chNull };
365 static const XMLCh UTF8[]={ chLatin_U, chLatin_T, chLatin_F, chDash, chDigit_8, chNull };
367 MemBufFormatTarget target;
368 DOMImplementation* impl=DOMImplementationRegistry::getDOMImplementation(impltype);
370 #ifdef XMLTOOLING_XERCESC_COMPLIANT_DOMLS
371 DOMLSSerializer* serializer = static_cast<DOMImplementationLS*>(impl)->createLSSerializer();
372 XercesJanitor<DOMLSSerializer> janitor(serializer);
373 if (pretty && serializer->getDomConfig()->canSetParameter(XMLUni::fgDOMWRTFormatPrettyPrint, pretty))
374 serializer->getDomConfig()->setParameter(XMLUni::fgDOMWRTFormatPrettyPrint, pretty);
375 DOMLSOutput *theOutput = static_cast<DOMImplementationLS*>(impl)->createLSOutput();
376 XercesJanitor<DOMLSOutput> j_theOutput(theOutput);
377 theOutput->setEncoding(UTF8);
378 theOutput->setByteStream(&target);
379 if (!serializer->write(n, theOutput))
380 throw XMLParserException("unable to serialize XML");
382 DOMWriter* serializer = static_cast<DOMImplementationLS*>(impl)->createDOMWriter();
383 XercesJanitor<DOMWriter> janitor(serializer);
384 serializer->setEncoding(UTF8);
385 if (pretty && serializer->canSetFeature(XMLUni::fgDOMWRTFormatPrettyPrint, pretty))
386 serializer->setFeature(XMLUni::fgDOMWRTFormatPrettyPrint, pretty);
387 if (!serializer->writeNode(&target, *n))
388 throw XMLParserException("unable to serialize XML");
392 buf.append(reinterpret_cast<const char*>(target.getRawBuffer()),target.getLen());
396 class StreamFormatTarget : public XMLFormatTarget
399 StreamFormatTarget(std::ostream& out) : m_out(out) {}
400 ~StreamFormatTarget() {}
402 void writeChars(const XMLByte *const toWrite, const xsecsize_t count, XMLFormatter *const formatter) {
403 m_out.write(reinterpret_cast<const char*>(toWrite),count);
415 ostream& XMLHelper::serialize(const DOMNode* n, ostream& out, bool pretty)
417 static const XMLCh impltype[] = { chLatin_L, chLatin_S, chNull };
418 static const XMLCh UTF8[]={ chLatin_U, chLatin_T, chLatin_F, chDash, chDigit_8, chNull };
420 StreamFormatTarget target(out);
421 DOMImplementation* impl=DOMImplementationRegistry::getDOMImplementation(impltype);
423 #ifdef XMLTOOLING_XERCESC_COMPLIANT_DOMLS
424 DOMLSSerializer* serializer = static_cast<DOMImplementationLS*>(impl)->createLSSerializer();
425 XercesJanitor<DOMLSSerializer> janitor(serializer);
426 if (pretty && serializer->getDomConfig()->canSetParameter(XMLUni::fgDOMWRTFormatPrettyPrint, pretty))
427 serializer->getDomConfig()->setParameter(XMLUni::fgDOMWRTFormatPrettyPrint, pretty);
428 DOMLSOutput *theOutput = static_cast<DOMImplementationLS*>(impl)->createLSOutput();
429 XercesJanitor<DOMLSOutput> j_theOutput(theOutput);
430 theOutput->setEncoding(UTF8);
431 theOutput->setByteStream(&target);
432 if (!serializer->write(n, theOutput))
433 throw XMLParserException("unable to serialize XML");
435 DOMWriter* serializer=(static_cast<DOMImplementationLS*>(impl))->createDOMWriter();
436 XercesJanitor<DOMWriter> janitor(serializer);
437 serializer->setEncoding(UTF8);
438 if (pretty && serializer->canSetFeature(XMLUni::fgDOMWRTFormatPrettyPrint, pretty))
439 serializer->setFeature(XMLUni::fgDOMWRTFormatPrettyPrint, pretty);
440 if (!serializer->writeNode(&target,*n))
441 throw XMLParserException("unable to serialize XML");
447 ostream& xmltooling::operator<<(ostream& ostr, const DOMNode& node)
449 return XMLHelper::serialize(&node, ostr);
452 ostream& xmltooling::operator<<(ostream& ostr, const XMLObject& obj)
454 return ostr << *(obj.marshall());