use of org.apache.axiom.om.impl.dom.TextImpl in project ballerina by ballerina-lang.
the class XMLUtils method parse.
/**
* Create a XML item from string literal.
*
* @param xmlStr String representation of the XML
* @return XML sequence
*/
@SuppressWarnings("unchecked")
public static BXML<?> parse(String xmlStr) {
try {
if (xmlStr.isEmpty()) {
return new BXMLItem(new TextImpl());
}
// If this is an XML document, parse it and return an element type XML.
if (xmlStr.trim().startsWith(XML_DCLR_START)) {
return new BXMLItem(xmlStr);
}
// Here we add a dummy enclosing tag, and send to AXIOM to parse the XML.
// This is to overcome the issue of axiom not allowing to parse xml-comments,
// xml-text nodes, and pi nodes, without having an enclosing xml-element node.
OMElement omElement = AXIOMUtil.stringToOM("<root>" + xmlStr + "</root>");
Iterator<OMNode> children = omElement.getChildren();
OMNode omNode = null;
if (children.hasNext()) {
omNode = children.next();
}
if (children.hasNext()) {
throw new BallerinaException("xml item must be one of the types: 'element', 'comment', 'text', 'pi'");
}
// Here the node is detached from the dummy root, and added to a
// document element. This is to get the xpath working correctly
omNode = omNode.detach();
OMDocument doc = OM_FACTORY.createOMDocument();
doc.addChild(omNode);
return new BXMLItem(omNode);
} catch (BallerinaException e) {
throw e;
} catch (OMException | XMLStreamException e) {
Throwable cause = e.getCause() == null ? e : e.getCause();
throw new BallerinaException(cause.getMessage());
} catch (Throwable e) {
throw new BallerinaException("failed to parse xml: " + e.getMessage());
}
}
use of org.apache.axiom.om.impl.dom.TextImpl in project ballerina by ballerina-lang.
the class BXMLItem method copy.
/**
* {@inheritDoc}
*/
@Override
public BXMLItem copy() {
OMNode clonedNode = null;
switch(nodeType) {
case ELEMENT:
clonedNode = ((OMElement) omNode).cloneOMElement();
break;
case TEXT:
TextImpl text = new TextImpl();
text.setTextContent(((OMText) omNode).getText());
clonedNode = text;
break;
case COMMENT:
CommentImpl comment = new CommentImpl();
comment.setTextContent(((OMComment) omNode).getValue());
clonedNode = comment;
break;
case PI:
OMProcessingInstructionImpl pi = new OMProcessingInstructionImpl();
pi.setTarget(((OMProcessingInstruction) omNode).getTarget());
pi.setValue(((OMProcessingInstruction) omNode).getValue());
clonedNode = pi;
break;
default:
clonedNode = omNode;
break;
}
// adding the document element as parent, to get xpPaths work
OMDocument doc = new OMDocumentImpl();
doc.addChild(clonedNode);
return new BXMLItem(clonedNode);
}
Aggregations