下面列出了怎么用org.w3c.dom.CharacterData的API类实例代码及写法,或者点击链接到github查看源代码。
@Override
protected void loadCustomXmlData(Element payloadNode) {
NodeList bodyTemplateElements = payloadNode.getElementsByTagName("BodyTemplate");
if (bodyTemplateElements.getLength() > 0) {
NodeList bodyNodes = bodyTemplateElements.item(0).getChildNodes();
for (int i = 0; i < bodyNodes.getLength(); i++) {
if (bodyNodes.item(i) instanceof CharacterData) {
CharacterData data = (CharacterData) bodyNodes.item(i);
mBodyTemplate = data.getData();
break;
}
}
}
setName(getNodeValue(payloadNode, "TemplateName"));
}
public void registerChildNodes(Node parentNode, boolean deep) {
if (parentNode.getUserData(SAAJ_NODE) == null) {
if (parentNode instanceof Element) {
ElementFactory.createElement(this, (Element) parentNode);
} else if (parentNode instanceof CharacterData) {
switch (parentNode.getNodeType()) {
case CDATA_SECTION_NODE:
new CDATAImpl(this, (CharacterData) parentNode);
break;
case COMMENT_NODE:
new SOAPCommentImpl(this, (CharacterData) parentNode);
break;
case TEXT_NODE:
new SOAPTextImpl(this, (CharacterData) parentNode);
break;
}
}
}
if (deep) {
NodeList nodeList = parentNode.getChildNodes();
for (int i = 0; i < nodeList.getLength(); i++) {
Node nextChild = nodeList.item(i);
registerChildNodes(nextChild, true);
}
}
}
@SuppressWarnings("PMD.AvoidInstantiatingObjectsInLoops")
public XmlElement(final Element element) {
this.name = element.getNodeName();
final NamedNodeMap attributes = element.getAttributes();
for (int i = 0; i < attributes.getLength(); i++) {
final Node item = attributes.item(i);
this.attributes.put(item.getNodeName(), item.getNodeValue());
}
final StringBuilder textValue = new StringBuilder();
final NodeList children = element.getChildNodes();
for (int i = 0; i < children.getLength(); i++) {
final Node node = children.item(i);
if (node.getNodeType() == Node.ELEMENT_NODE) {
this.children.add(new XmlElement((Element) node));
}
if (node.getNodeType() == Node.TEXT_NODE) {
textValue.append(node.getNodeValue());
}
if (node.getNodeType() == Node.CDATA_SECTION_NODE) {
textValue.append(((CharacterData) node).getData());
}
}
this.value = textValue.toString();
}
/**
* Concatenate nodes for xpath
* @param itemXml
* @param xpath
* @return
*/
protected String makeItemNodeText(Item itemXml, String xpath)
{
//String text = "";
List nodes = itemXml.selectNodes(xpath);
Iterator iter = nodes.iterator();
StringBuilder textbuf = new StringBuilder();
while (iter.hasNext())
{
Node node = (Node) iter.next();
Node child = node.getFirstChild();
if ( (child != null) && child instanceof CharacterData)
{
CharacterData cdi = (CharacterData) child;
textbuf.append(" " + cdi.getData());
}
}
String text = textbuf.toString();
return text;
}
private boolean matchText(Element parent,
String match) {
NodeList children = parent.getChildNodes();
for (int i=0; i<children.getLength(); i++) {
Node child = children.item(i);
if (child.getNodeType() == Node.ELEMENT_NODE) {
Element e = (Element) child;
if (! matchText(e, match)) {
return false;
}
} else if (child.getNodeType() == Node.TEXT_NODE ||
child.getNodeType() == Node.CDATA_SECTION_NODE) {
String data = ((CharacterData) child).getData();
if (! matchText(data, match)) {
return false;
}
} // else we skip the node
}
return true;
}
/**
* getDataFromElement - Make XML parsing a bit easier
* @param e XML Element
* @return XML data as a String
*/
public static String getDataFromElement(Element e) {
try {
Node child = e.getFirstChild();
if (child instanceof CharacterData) {
CharacterData cd = (CharacterData) child;
return cd.getData();
}
}
catch (Exception ex) {
logger.debug("Error in getDataFromElement");
logger.debug(ex.getMessage());
logger.debug(ex.getStackTrace());
}
return "";
}
/**
* Concatenate nodes for xpath
* @param itemXml
* @param xpath
* @return
*/
protected String makeItemNodeText(Item itemXml, String xpath)
{
//String text = "";
List nodes = itemXml.selectNodes(xpath);
Iterator iter = nodes.iterator();
StringBuilder textbuf = new StringBuilder();
while (iter.hasNext())
{
Node node = (Node) iter.next();
Node child = node.getFirstChild();
if ( (child != null) && child instanceof CharacterData)
{
CharacterData cdi = (CharacterData) child;
textbuf.append(" " + cdi.getData());
}
}
String text = textbuf.toString();
return text;
}
/**
* Extracts the text value from the given DOM element, ignoring XML comments.
* <p>Appends all CharacterData nodes and EntityReference nodes into a single
* String value, excluding Comment nodes. Only exposes actual user-specified
* text, no default values of any kind.
* @see CharacterData
* @see EntityReference
* @see Comment
*/
public static String getTextValue(Element valueEle) {
Assert.notNull(valueEle, "Element must not be null");
StringBuilder sb = new StringBuilder();
NodeList nl = valueEle.getChildNodes();
for (int i = 0; i < nl.getLength(); i++) {
Node item = nl.item(i);
if ((item instanceof CharacterData && !(item instanceof Comment)) || item instanceof EntityReference) {
sb.append(item.getNodeValue());
}
}
return sb.toString();
}
/**
* Extracts the text value from the given DOM element, ignoring XML comments.
* <p>Appends all CharacterData nodes and EntityReference nodes into a single
* String value, excluding Comment nodes. Only exposes actual user-specified
* text, no default values of any kind.
* @see CharacterData
* @see EntityReference
* @see Comment
*/
public static String getTextValue(Element valueEle) {
Assert.notNull(valueEle, "Element must not be null");
StringBuilder sb = new StringBuilder();
NodeList nl = valueEle.getChildNodes();
for (int i = 0; i < nl.getLength(); i++) {
Node item = nl.item(i);
if ((item instanceof CharacterData && !(item instanceof Comment)) || item instanceof EntityReference) {
sb.append(item.getNodeValue());
}
}
return sb.toString();
}
/**
* Extract the text value from the given DOM element, ignoring XML comments. <p>Appends all CharacterData nodes and
* EntityReference nodes into a single String value, excluding Comment nodes.
*
* @see CharacterData
* @see EntityReference
* @see Comment
*/
public static String getTextValue(Element valueEle) {
if(valueEle == null) throw new IllegalArgumentException("Element must not be null");
StringBuilder sb = new StringBuilder();
NodeList nl = valueEle.getChildNodes();
for (int i = 0; i < nl.getLength(); i++) {
Node item = nl.item(i);
if ((item instanceof CharacterData && !(item instanceof Comment)) || item instanceof EntityReference) {
sb.append(item.getNodeValue());
}else if(item instanceof Element) {
sb.append(getTextValue((Element)item));
}
}
return sb.toString();
}
public static String getNodeValue(Node node) {
if(node instanceof Comment){
return null;
}
if(node instanceof CharacterData) {
return ((CharacterData)node).getData();
}
if(node instanceof EntityReference) {
return node.getNodeValue();
}
if(node instanceof Element) {
return getTextValue((Element)node);
}
return node.getNodeValue();
}
public ConfigStore getConfigStore() {
DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder documentBuilder;
String value;
try {
documentBuilder = documentBuilderFactory.newDocumentBuilder();
Document doc = documentBuilder.parse(stream);
doc.getDocumentElement().normalize();
NodeList nodeList = doc.getElementsByTagName("configuration").item(0).getChildNodes();
for (int ix = 0; ix < nodeList.getLength(); ix++) {
Node node = nodeList.item(ix);
Element el = node.getNodeType() == Node.ELEMENT_NODE ? (Element) node : null;
if (el != null) {
value = el.getTextContent();
value = el instanceof CharacterData ? ((CharacterData) el).getData() : value;
store.addConfig(el.getNodeName(), value);
}
}
return store;
} catch (IOException | SAXException | ParserConfigurationException e) {
LOG.log(Level.SEVERE, "Failed to load external configuration", e);
}
return null;
}
/**
* Logs in to turnitin. Scrapes the response XML and returns the session id
* or throws an exception if it was unable to log in.
*
* @param conn
* @param params This function will take care of the fids/fcmds. Just make
* sure this has the defaults you use for every TII call as well as the
* user info including utp (even though utp doesn't seem to make sense
* since this doesn't include a course id parameter.)
* @return session-id for use in other turnitin calls.
* @throws TransientSubmissionException
* @throws SubmissionException
*/
public static String getTurnitinSession(TurnitinAccountConnection conn,
@SuppressWarnings("rawtypes") Map params) throws
TransientSubmissionException, SubmissionException {
Map finalParams = new HashMap();
finalParams.putAll(params);
finalParams.put("fid", "17");
finalParams.put("fcmd", "2");
Document doc = conn.callTurnitinReturnDocument(finalParams);
Element root = doc.getDocumentElement();
int rcode = new Integer(((CharacterData)
(root.getElementsByTagName("rcode").item(0).getFirstChild())).getData().trim()).intValue();
String message = ((CharacterData)
(root.getElementsByTagName("rmessage").item(0).getFirstChild())).getData().trim();
if (!(rcode > 0 && rcode < 100)) {
throw new TransientSubmissionException("Error logging in to turnitin: " + message);
}
String sessionId = ((CharacterData)
(root.getElementsByTagName("sessionid").item(0).getFirstChild())).getData().trim();
log.debug("Log in results. rcode: " + rcode + " message: " + message +
" sessionId: " + sessionId);
return sessionId;
}
protected TextImpl convertToSoapText(CharacterData characterData) {
final Node soapNode = getSoapDocument().findIfPresent(characterData);
if (soapNode instanceof TextImpl) {
return (TextImpl) soapNode;
} else {
TextImpl t = null;
switch (characterData.getNodeType()) {
case CDATA_SECTION_NODE:
t = new CDATAImpl(getSoapDocument(), characterData.getData());
break;
case COMMENT_NODE:
t = new SOAPCommentImpl(getSoapDocument(), characterData.getData());
break;
case TEXT_NODE:
t = new SOAPTextImpl(getSoapDocument(), characterData.getData());
break;
}
Node parent = getSoapDocument().find(characterData.getParentNode());
if (parent != null) {
parent.replaceChild(t, characterData);
} // XXX else throw an exception?
return t;
// return replaceElementWithSOAPElement(
// element,
// (ElementImpl) createElement(NameImpl.copyElementName(element)));
}
}
public static String getCharacterDataFromElement(Element e)
{
Node child = e.getFirstChild();
if (child instanceof CharacterData) {
CharacterData cd = (CharacterData) child;
return cd.getData();
}
return "?";
}
public static String contents(Node node) throws Exception {
if (node instanceof Attr) {
return contents((Attr) node);
}
if (node instanceof CharacterData) {
return contents((CharacterData) node);
}
if (node instanceof Element) {
return contents((Element) node);
}
throw new UnsupportedOperationException("Unknown node type " + node.getClass());
}
public static String getCharacterDataFromElement(Element e) {
Node child = e.getFirstChild();
if (child instanceof CharacterData) {
CharacterData cd = (CharacterData) child;
return cd.getData();
}
return "?";
}
@Test
public void testAppendData() throws Exception {
CharacterData cd = createCharacterData("DOM");
cd.appendData("2");
assertEquals(cd.getData(), "DOM2");
}
private boolean hasNewline(Node n) {
if (n instanceof Comment) {
return false;
}
CharacterData c = (CharacterData) n;
return (-1) != c.getData().indexOf('\n');
}
@Test(dataProvider = "data-for-insert-neg")
public void testInsertDataNeg(String text, int offset) throws Exception {
CharacterData cd = createCharacterData(text);
try {
cd.insertData(offset, "TEST");
fail(DOMEXCEPTION_EXPECTED);
} catch (DOMException e) {
assertEquals(e.code, INDEX_SIZE_ERR);
}
}
public static String getCharacterDataFromElement(Element e) {
Node child = e.getFirstChild();
if (child instanceof CharacterData) {
CharacterData cd = (CharacterData) child;
return cd.getData();
}
return "?";
}
private String getBodyData(Node child) {
if (child.getNodeType() == Node.CDATA_SECTION_NODE || child.getNodeType() == Node.TEXT_NODE) {
String data = ((CharacterData) child).getData();
// TODO data = PropertyParser.parse(data, null);
return data;
}
return null;
}
public static String getCharacterDataFromElement(Element e) {
org.w3c.dom.Node child = e.getFirstChild();
if (child instanceof CharacterData) {
CharacterData cd = (CharacterData) child;
return cd.getData();
} else {
return "?";
}
}
/**
* Extracts the text value from the given DOM element, ignoring XML comments.
* <p>Appends all CharacterData nodes and EntityReference nodes into a single
* String value, excluding Comment nodes. Only exposes actual user-specified
* text, no default values of any kind.
* @see CharacterData
* @see EntityReference
* @see Comment
*/
public static String getTextValue(Element valueEle) {
Assert.notNull(valueEle, "Element must not be null");
StringBuilder sb = new StringBuilder();
NodeList nl = valueEle.getChildNodes();
for (int i = 0; i < nl.getLength(); i++) {
Node item = nl.item(i);
if ((item instanceof CharacterData && !(item instanceof Comment)) || item instanceof EntityReference) {
sb.append(item.getNodeValue());
}
}
return sb.toString();
}
private String getBodyData(Node child) {
if (child.getNodeType() == Node.CDATA_SECTION_NODE
|| child.getNodeType() == Node.TEXT_NODE) {
String data = ((CharacterData) child).getData();
data = PropertyParser.parse(data, variables);
return data;
}
return null;
}
/**
* This method was originally private, but is being made public for the
* moment so we can run integration tests. TODO Revisit this decision.
*
* @param siteId
* @throws SubmissionException
* @throws TransientSubmissionException
*/
@SuppressWarnings("unchecked")
public void createClass(String siteId) throws SubmissionException, TransientSubmissionException {
log.debug("Creating class for site: " + siteId);
String cpw = defaultClassPassword;
String ctl = siteId;
String fcmd = "2";
String fid = "2";
String utp = "2"; // user type 2 = instructor
String cid = siteId;
Document document = null;
Map params = TurnitinAPIUtil.packMap(turnitinConn.getBaseTIIOptions(), "cid", cid, "cpw", cpw, "ctl", ctl,
"fcmd", fcmd, "fid", fid, "utp", utp);
params.putAll(getInstructorInfo(siteId));
document = turnitinConn.callTurnitinReturnDocument(params);
Element root = document.getDocumentElement();
String rcode = ((CharacterData) (root.getElementsByTagName("rcode").item(0).getFirstChild())).getData().trim();
if (((CharacterData) (root.getElementsByTagName("rcode").item(0).getFirstChild())).getData().trim()
.compareTo("20") == 0
|| ((CharacterData) (root.getElementsByTagName("rcode").item(0).getFirstChild())).getData().trim()
.compareTo("21") == 0) {
log.debug("Create Class successful");
} else {
String rmessage = ((CharacterData) (root.getElementsByTagName("rmessage").item(0).getFirstChild())).getData().trim();
throw new ContentReviewProviderException(getFormattedMessage("enrolment.class.creation.error.with.code", rmessage, rcode),
createLastError(doc->createFormattedMessageXML(doc, "enrolment.class.creation.error.with.code", rmessage, rcode)));
}
}
/**
* convert the value of a given XML element to a string for further processing
*
* @param e
* XML Element
* @return the elements value converted to string
*/
private static String getCharacterDataFromElement(Element e) {
final Node child = e.getFirstChild();
if (child instanceof CharacterData) {
final CharacterData cd = (CharacterData) child;
return cd.getData();
}
return "";
}
/**
* Logs in to turnitin. Scrapes the response XML and returns the session id
* or throws an exception if it was unable to log in.
*
* @param conn
* @param params This function will take care of the fids/fcmds. Just make
* sure this has the defaults you use for every TII call as well as the
* user info including utp (even though utp doesn't seem to make sense
* since this doesn't include a course id parameter.)
* @return session-id for use in other turnitin calls.
* @throws TransientSubmissionException
* @throws SubmissionException
*/
public static String getTurnitinSession(TurnitinAccountConnection conn,
@SuppressWarnings("rawtypes") Map params) throws
TransientSubmissionException, SubmissionException {
Map finalParams = new HashMap();
finalParams.putAll(params);
finalParams.put("fid", "17");
finalParams.put("fcmd", "2");
Document doc = conn.callTurnitinReturnDocument(finalParams);
Element root = doc.getDocumentElement();
int rcode = new Integer(((CharacterData)
(root.getElementsByTagName("rcode").item(0).getFirstChild())).getData().trim()).intValue();
String message = ((CharacterData)
(root.getElementsByTagName("rmessage").item(0).getFirstChild())).getData().trim();
if (!(rcode > 0 && rcode < 100)) {
throw new TransientSubmissionException("Error logging in to turnitin: " + message);
}
String sessionId = ((CharacterData)
(root.getElementsByTagName("sessionid").item(0).getFirstChild())).getData().trim();
log.debug("Log in results. rcode: " + rcode + " message: " + message +
" sessionId: " + sessionId);
return sessionId;
}
private static void writeNode(Node n, XMLStreamWriter writer) throws XMLStreamException {
if (n.getNodeType() == Node.ELEMENT_NODE) {
writeElement((Element) n, writer);
} else if (n.getNodeType() == Node.CDATA_SECTION_NODE || n.getNodeType() == Node.TEXT_NODE) {
writeCharacters((CharacterData) n, writer);
} else {
LOG.warn("Skipping element " + n.getNodeName());
}
}
public final void setNodeValue(String nodeValue) throws DOMException {
switch (getNodeType()) {
case CDATA_SECTION_NODE:
case COMMENT_NODE:
case TEXT_NODE:
((CharacterData) this).setData(nodeValue);
return;
case PROCESSING_INSTRUCTION_NODE:
((ProcessingInstruction) this).setData(nodeValue);
return;
case ATTRIBUTE_NODE:
((Attr) this).setValue(nodeValue);
return;
case ELEMENT_NODE:
case ENTITY_REFERENCE_NODE:
case ENTITY_NODE:
case DOCUMENT_NODE:
case DOCUMENT_TYPE_NODE:
case DOCUMENT_FRAGMENT_NODE:
case NOTATION_NODE:
return; // do nothing!
default:
throw new DOMException(DOMException.NOT_SUPPORTED_ERR,
"Unsupported node type " + getNodeType());
}
}