2 * Copyright 2001-2010 Internet2
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
20 * A helper class for working with W3C DOM objects.
24 #include "exceptions.h"
26 #include "XMLObject.h"
27 #include "util/XMLHelper.h"
28 #include "util/XMLConstants.h"
30 #include <xercesc/framework/MemBufFormatTarget.hpp>
31 #include <xercesc/util/XMLUniDefs.hpp>
33 using namespace xmltooling;
34 using namespace xercesc;
37 static const XMLCh type[]={chLatin_t, chLatin_y, chLatin_p, chLatin_e, chNull };
39 bool XMLHelper::hasXSIType(const DOMElement* e)
41 return (e && e->hasAttributeNS(xmlconstants::XSI_NS, type));
44 xmltooling::QName* XMLHelper::getXSIType(const DOMElement* e)
46 DOMAttr* attribute = e->getAttributeNodeNS(xmlconstants::XSI_NS, type);
48 const XMLCh* attributeValue = attribute->getTextContent();
49 if (attributeValue && *attributeValue) {
51 if ((i=XMLString::indexOf(attributeValue,chColon))>0) {
52 XMLCh* prefix=new XMLCh[i+1];
53 XMLString::subString(prefix,attributeValue,0,i);
55 xmltooling::QName* ret=new xmltooling::QName(e->lookupNamespaceURI(prefix), attributeValue + i + 1, prefix);
60 return new xmltooling::QName(e->lookupNamespaceURI(nullptr), attributeValue);
68 DOMAttr* XMLHelper::getIdAttribute(const DOMElement* domElement)
70 if(!domElement->hasAttributes()) {
74 DOMNamedNodeMap* attributes = domElement->getAttributes();
76 for(XMLSize_t i = 0; i < attributes->getLength(); i++) {
77 attribute = static_cast<DOMAttr*>(attributes->item(i));
78 if(attribute->isId()) {
86 const XMLObject* XMLHelper::getXMLObjectById(const XMLObject& tree, const XMLCh* id)
88 if (XMLString::equals(id, tree.getXMLID()))
92 const list<XMLObject*>& children = tree.getOrderedChildren();
93 for (list<XMLObject*>::const_iterator i=children.begin(); i!=children.end(); ++i) {
95 ret = getXMLObjectById(*(*i), id);
104 XMLObject* XMLHelper::getXMLObjectById(XMLObject& tree, const XMLCh* id)
106 if (XMLString::equals(id, tree.getXMLID()))
110 const list<XMLObject*>& children = tree.getOrderedChildren();
111 for (list<XMLObject*>::const_iterator i=children.begin(); i!=children.end(); ++i) {
113 ret = getXMLObjectById(*(*i), id);
122 void XMLHelper::getNonVisiblyUsedPrefixes(const XMLObject& tree, map<xstring,xstring>& prefixes)
124 map<xstring,xstring> child_prefixes;
125 const list<XMLObject*>& children = tree.getOrderedChildren();
126 for (list<XMLObject*>::const_iterator i = children.begin(); i != children.end(); ++i) {
128 getNonVisiblyUsedPrefixes(*(*i), child_prefixes);
130 const set<Namespace>& nsset = tree.getNamespaces();
131 for (set<Namespace>::const_iterator ns = nsset.begin(); ns != nsset.end(); ++ns) {
132 // Check for xmlns:xml.
133 if (XMLString::equals(ns->getNamespacePrefix(), xmlconstants::XML_PREFIX) && XMLString::equals(ns->getNamespaceURI(), xmlconstants::XML_NS))
135 switch (ns->usage()) {
136 case Namespace::Indeterminate:
138 case Namespace::VisiblyUsed:
140 // See if the prefix was noted as non-visible below.
141 const XMLCh* p = ns->getNamespacePrefix() ? ns->getNamespacePrefix() : &chNull;
142 map<xstring,xstring>::iterator decl = child_prefixes.find(p);
143 if (decl != child_prefixes.end()) {
144 // It's declared below, see if it's the same namespace. If so, pull it from the set,
145 // otherwise leave it in the set.
146 if (decl->second == (ns->getNamespaceURI() ? ns->getNamespaceURI() : &chNull))
147 child_prefixes.erase(decl);
151 case Namespace::NonVisiblyUsed:
152 // It may already be in the map from another branch of the tree, but as long
153 // as it's set to something so the parent knows about it, we're good.
154 prefixes[ns->getNamespacePrefix() ? ns->getNamespacePrefix() : &chNull] = (ns->getNamespaceURI() ? ns->getNamespaceURI() : &chNull);
159 prefixes.insert(child_prefixes.begin(), child_prefixes.end());
162 xmltooling::QName* XMLHelper::getNodeQName(const DOMNode* domNode)
165 return new xmltooling::QName(domNode->getNamespaceURI(), domNode->getLocalName(), domNode->getPrefix());
169 xmltooling::QName* XMLHelper::getAttributeValueAsQName(const DOMAttr* attribute)
171 return getNodeValueAsQName(attribute);
174 xmltooling::QName* XMLHelper::getNodeValueAsQName(const DOMNode* domNode)
180 const XMLCh* value=domNode->getTextContent();
181 if (value && (i=XMLString::indexOf(value,chColon))>0) {
182 XMLCh* prefix=new XMLCh[i+1];
183 XMLString::subString(prefix,value,0,i);
185 xmltooling::QName* ret=new xmltooling::QName(domNode->lookupNamespaceURI(prefix), value + i + 1, prefix);
190 return new xmltooling::QName(domNode->lookupNamespaceURI(nullptr), value);
193 bool XMLHelper::getNodeValueAsBool(const xercesc::DOMNode* domNode, bool def)
197 const XMLCh* value = domNode->getNodeValue();
198 if (!value || !*value)
200 if (*value == chLatin_t || *value == chDigit_1)
202 else if (*value == chLatin_f || *value == chDigit_0)
207 DOMElement* XMLHelper::appendChildElement(DOMElement* parentElement, DOMElement* childElement)
209 DOMDocument* parentDocument = parentElement->getOwnerDocument();
210 if (childElement->getOwnerDocument() != parentDocument) {
211 childElement = static_cast<DOMElement*>(parentDocument->importNode(childElement, true));
214 parentElement->appendChild(childElement);
218 bool XMLHelper::isNodeNamed(const xercesc::DOMNode* n, const XMLCh* ns, const XMLCh* local)
220 return (n && XMLString::equals(local,n->getLocalName()) && XMLString::equals(ns,n->getNamespaceURI()));
223 const XMLCh* XMLHelper::getTextContent(const DOMElement* e)
225 DOMNode* child = e ? e->getFirstChild() : nullptr;
227 if (child->getNodeType() == DOMNode::TEXT_NODE)
228 return child->getNodeValue();
229 child = child->getNextSibling();
234 DOMElement* XMLHelper::getFirstChildElement(const DOMNode* n, const XMLCh* localName)
236 DOMNode* child = n ? n->getFirstChild() : nullptr;
237 while (child && child->getNodeType() != DOMNode::ELEMENT_NODE)
238 child = child->getNextSibling();
239 if (child && localName) {
240 if (!XMLString::equals(localName,child->getLocalName()))
241 return getNextSiblingElement(child, localName);
243 return static_cast<DOMElement*>(child);
246 DOMElement* XMLHelper::getLastChildElement(const DOMNode* n, const XMLCh* localName)
248 DOMNode* child = n ? n->getLastChild() : nullptr;
249 while (child && child->getNodeType() != DOMNode::ELEMENT_NODE)
250 child = child->getPreviousSibling();
251 if (child && localName) {
252 if (!XMLString::equals(localName,child->getLocalName()))
253 return getPreviousSiblingElement(child, localName);
255 return static_cast<DOMElement*>(child);
258 DOMElement* XMLHelper::getFirstChildElement(const DOMNode* n, const XMLCh* ns, const XMLCh* localName)
260 DOMElement* e = getFirstChildElement(n, localName);
261 while (e && !XMLString::equals(e->getNamespaceURI(),ns))
262 e = getNextSiblingElement(e, localName);
266 DOMElement* XMLHelper::getLastChildElement(const DOMNode* n, const XMLCh* ns, const XMLCh* localName)
268 DOMElement* e = getLastChildElement(n, localName);
269 while (e && !XMLString::equals(e->getNamespaceURI(),ns))
270 e = getPreviousSiblingElement(e, localName);
274 DOMElement* XMLHelper::getNextSiblingElement(const DOMNode* n, const XMLCh* localName)
276 DOMNode* sib = n ? n->getNextSibling() : nullptr;
277 while (sib && sib->getNodeType() != DOMNode::ELEMENT_NODE)
278 sib = sib->getNextSibling();
279 if (sib && localName) {
280 if (!XMLString::equals(localName,sib->getLocalName()))
281 return getNextSiblingElement(sib, localName);
283 return static_cast<DOMElement*>(sib);
286 DOMElement* XMLHelper::getPreviousSiblingElement(const DOMNode* n, const XMLCh* localName)
288 DOMNode* sib = n ? n->getPreviousSibling() : nullptr;
289 while (sib && sib->getNodeType() != DOMNode::ELEMENT_NODE)
290 sib = sib->getPreviousSibling();
291 if (sib && localName) {
292 if (!XMLString::equals(localName,sib->getLocalName()))
293 return getPreviousSiblingElement(sib, localName);
295 return static_cast<DOMElement*>(sib);
298 DOMElement* XMLHelper::getNextSiblingElement(const DOMNode* n, const XMLCh* ns, const XMLCh* localName)
300 DOMElement* e = getNextSiblingElement(n, localName);
301 while (e && !XMLString::equals(e->getNamespaceURI(),ns))
302 e = getNextSiblingElement(e, localName);
306 DOMElement* XMLHelper::getPreviousSiblingElement(const DOMNode* n, const XMLCh* ns, const XMLCh* localName)
308 DOMElement* e = getPreviousSiblingElement(n, localName);
309 while (e && !XMLString::equals(e->getNamespaceURI(),ns))
310 e = getPreviousSiblingElement(e, localName);
314 string XMLHelper::getAttrString(const DOMElement* e, const char* defValue, const XMLCh* localName, const XMLCh* ns)
317 auto_ptr_char val(e->getAttributeNS(ns, localName));
318 if (val.get() && *val.get())
321 return defValue ? defValue : "";
324 int XMLHelper::getAttrInt(const DOMElement* e, int defValue, const XMLCh* localName, const XMLCh* ns)
327 const XMLCh* val = e->getAttributeNS(ns, localName);
329 int i = XMLString::parseInt(val);
337 bool XMLHelper::getAttrBool(const DOMElement* e, bool defValue, const XMLCh* localName, const XMLCh* ns)
340 const XMLCh* val = e->getAttributeNS(ns, localName);
342 if (*val == chLatin_t || *val == chDigit_1)
344 if (*val == chLatin_f || *val == chDigit_0)
351 void XMLHelper::serialize(const DOMNode* n, std::string& buf, bool pretty)
353 static const XMLCh impltype[] = { chLatin_L, chLatin_S, chNull };
354 static const XMLCh UTF8[]={ chLatin_U, chLatin_T, chLatin_F, chDash, chDigit_8, chNull };
356 MemBufFormatTarget target;
357 DOMImplementation* impl=DOMImplementationRegistry::getDOMImplementation(impltype);
359 #ifdef XMLTOOLING_XERCESC_COMPLIANT_DOMLS
360 DOMLSSerializer* serializer = static_cast<DOMImplementationLS*>(impl)->createLSSerializer();
361 XercesJanitor<DOMLSSerializer> janitor(serializer);
362 if (pretty && serializer->getDomConfig()->canSetParameter(XMLUni::fgDOMWRTFormatPrettyPrint, pretty))
363 serializer->getDomConfig()->setParameter(XMLUni::fgDOMWRTFormatPrettyPrint, pretty);
364 DOMLSOutput *theOutput = static_cast<DOMImplementationLS*>(impl)->createLSOutput();
365 XercesJanitor<DOMLSOutput> j_theOutput(theOutput);
366 theOutput->setEncoding(UTF8);
367 theOutput->setByteStream(&target);
368 if (!serializer->write(n, theOutput))
369 throw XMLParserException("unable to serialize XML");
371 DOMWriter* serializer = static_cast<DOMImplementationLS*>(impl)->createDOMWriter();
372 XercesJanitor<DOMWriter> janitor(serializer);
373 serializer->setEncoding(UTF8);
374 if (pretty && serializer->canSetFeature(XMLUni::fgDOMWRTFormatPrettyPrint, pretty))
375 serializer->setFeature(XMLUni::fgDOMWRTFormatPrettyPrint, pretty);
376 if (!serializer->writeNode(&target, *n))
377 throw XMLParserException("unable to serialize XML");
381 buf.append(reinterpret_cast<const char*>(target.getRawBuffer()),target.getLen());
385 class StreamFormatTarget : public XMLFormatTarget
388 StreamFormatTarget(std::ostream& out) : m_out(out) {}
389 ~StreamFormatTarget() {}
391 void writeChars(const XMLByte *const toWrite, const xsecsize_t count, XMLFormatter *const formatter) {
392 m_out.write(reinterpret_cast<const char*>(toWrite),count);
404 ostream& XMLHelper::serialize(const DOMNode* n, ostream& out, bool pretty)
406 static const XMLCh impltype[] = { chLatin_L, chLatin_S, chNull };
407 static const XMLCh UTF8[]={ chLatin_U, chLatin_T, chLatin_F, chDash, chDigit_8, chNull };
409 StreamFormatTarget target(out);
410 DOMImplementation* impl=DOMImplementationRegistry::getDOMImplementation(impltype);
412 #ifdef XMLTOOLING_XERCESC_COMPLIANT_DOMLS
413 DOMLSSerializer* serializer = static_cast<DOMImplementationLS*>(impl)->createLSSerializer();
414 XercesJanitor<DOMLSSerializer> janitor(serializer);
415 if (pretty && serializer->getDomConfig()->canSetParameter(XMLUni::fgDOMWRTFormatPrettyPrint, pretty))
416 serializer->getDomConfig()->setParameter(XMLUni::fgDOMWRTFormatPrettyPrint, pretty);
417 DOMLSOutput *theOutput = static_cast<DOMImplementationLS*>(impl)->createLSOutput();
418 XercesJanitor<DOMLSOutput> j_theOutput(theOutput);
419 theOutput->setEncoding(UTF8);
420 theOutput->setByteStream(&target);
421 if (!serializer->write(n, theOutput))
422 throw XMLParserException("unable to serialize XML");
424 DOMWriter* serializer=(static_cast<DOMImplementationLS*>(impl))->createDOMWriter();
425 XercesJanitor<DOMWriter> janitor(serializer);
426 serializer->setEncoding(UTF8);
427 if (pretty && serializer->canSetFeature(XMLUni::fgDOMWRTFormatPrettyPrint, pretty))
428 serializer->setFeature(XMLUni::fgDOMWRTFormatPrettyPrint, pretty);
429 if (!serializer->writeNode(&target,*n))
430 throw XMLParserException("unable to serialize XML");
436 ostream& xmltooling::operator<<(ostream& ostr, const DOMNode& node)
438 return XMLHelper::serialize(&node, ostr);
441 ostream& xmltooling::operator<<(ostream& ostr, const XMLObject& obj)
443 return ostr << *(obj.marshall());