下面列出了怎么用org.w3c.dom.Text的API类实例代码及写法,或者点击链接到github查看源代码。
private void collectBaseContainer(Element e) {
for (Node n = e.getFirstChild(); n != null; n = n.getNextSibling()) {
if (n instanceof Text) {
// ignore #PCDATA
} else if (n instanceof Element) {
Element c = (Element) n;
if (Documents.isElement(c, ttSpanElementName)) {
Annotation annotation = styleCollector.getAnnotation(c);
if (annotation == null) {
// ignore span children that do not specify tts:ruby
} else if (annotation == Annotation.BASE) {
collectBase(c);
} else {
// ignore non-base annotation children
}
} else {
// ignore non-span children
}
}
}
}
/**
* Receive notification of character data.
*
* <p>The Parser will call this method to report each chunk of
* character data. SAX parsers may return all contiguous character
* data in a single chunk, or they may split it into several
* chunks; however, all of the characters in any single event
* must come from the same external entity, so that the Locator
* provides useful information.</p>
*
* <p>The application must not attempt to read from the array
* outside of the specified range.</p>
*
* <p>Note that some parsers will report whitespace using the
* ignorableWhitespace() method rather than this one (validating
* parsers must do so).</p>
*
* @param ch The characters from the XML document.
* @param start The start position in the array.
* @param length The number of characters to read from the array.
* @see #ignorableWhitespace
* @see org.xml.sax.Locator
*/
public void characters(char ch[], int start, int length) throws org.xml.sax.SAXException
{
if(isOutsideDocElem()
&& com.sun.org.apache.xml.internal.utils.XMLCharacterRecognizer.isWhiteSpace(ch, start, length))
return; // avoid DOM006 Hierarchy request error
if (m_inCData)
{
cdata(ch, start, length);
return;
}
String s = new String(ch, start, length);
Node childNode;
childNode = m_currentNode != null ? m_currentNode.getLastChild(): null;
if( childNode != null && childNode.getNodeType() == Node.TEXT_NODE ){
((Text)childNode).appendData(s);
}
else{
Text text = m_doc.createTextNode(s);
append(text);
}
}
@Test
public void marshalEmptyDOMResult() throws Exception {
DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
documentBuilderFactory.setNamespaceAware(true);
DocumentBuilder builder = documentBuilderFactory.newDocumentBuilder();
DOMResult domResult = new DOMResult();
marshaller.marshal(flights, domResult);
assertTrue("DOMResult does not contain a Document", domResult.getNode() instanceof Document);
Document result = (Document) domResult.getNode();
Document expected = builder.newDocument();
Element flightsElement = expected.createElementNS("http://samples.springframework.org/flight", "tns:flights");
Attr namespace = expected.createAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns:tns");
namespace.setNodeValue("http://samples.springframework.org/flight");
flightsElement.setAttributeNode(namespace);
expected.appendChild(flightsElement);
Element flightElement = expected.createElementNS("http://samples.springframework.org/flight", "tns:flight");
flightsElement.appendChild(flightElement);
Element numberElement = expected.createElementNS("http://samples.springframework.org/flight", "tns:number");
flightElement.appendChild(numberElement);
Text text = expected.createTextNode("42");
numberElement.appendChild(text);
assertThat("Marshaller writes invalid DOMResult", result, isSimilarTo(expected));
}
/**
* Checks if an Text node is well-formed, by checking if it contains invalid
* XML characters.
*
* @param data The contents of the comment node
*/
protected void isTextWellFormed(Text node) {
// Does the data valid XML character data
Character invalidChar = isWFXMLChar(node.getData());
if (invalidChar != null) {
String msg =
Utils.messages.createMessage(
MsgKey.ER_WF_INVALID_CHARACTER_IN_TEXT,
new Object[] { Integer.toHexString(Character.getNumericValue(invalidChar.charValue())) });
if (fErrorHandler != null) {
fErrorHandler.handleError(
new DOMErrorImpl(
DOMError.SEVERITY_FATAL_ERROR,
msg,
MsgKey.ER_WF_INVALID_CHARACTER,
null,
null,
null));
}
}
}
/**
* Method engineGetContextFromElement
*
* @param element
*/
protected void engineGetContextFromElement(Element element) {
super.engineGetContextFromElement(element);
if (element == null) {
throw new IllegalArgumentException("element null");
}
Text hmaclength =
XMLUtils.selectDsNodeText(element.getFirstChild(), Constants._TAG_HMACOUTPUTLENGTH, 0);
if (hmaclength != null) {
this.HMACOutputLength = Integer.parseInt(hmaclength.getData());
this.HMACOutputLengthSet = true;
}
}
public static Element nextElement(Iterator iter) {
while (iter.hasNext()) {
Node n = (Node) iter.next();
if (n instanceof Text) {
Text t = (Text) n;
if (t.getData().trim().length() == 0)
continue;
fail("parsing.nonWhitespaceTextFound", t.getData().trim());
}
if (n instanceof Comment)
continue;
if (!(n instanceof Element))
fail("parsing.elementExpected");
return (Element) n;
}
return null;
}
/**
* Method getStrFromNode
*
* @param xpathnode
* @return the string for the node.
*/
public static String getStrFromNode(Node xpathnode) {
if (xpathnode.getNodeType() == Node.TEXT_NODE) {
// we iterate over all siblings of the context node because eventually,
// the text is "polluted" with pi's or comments
StringBuilder sb = new StringBuilder();
for (Node currentSibling = xpathnode.getParentNode().getFirstChild();
currentSibling != null;
currentSibling = currentSibling.getNextSibling()) {
if (currentSibling.getNodeType() == Node.TEXT_NODE) {
sb.append(((Text) currentSibling).getData());
}
}
return sb.toString();
} else if (xpathnode.getNodeType() == Node.ATTRIBUTE_NODE) {
return ((Attr) xpathnode).getNodeValue();
} else if (xpathnode.getNodeType() == Node.PROCESSING_INSTRUCTION_NODE) {
return ((ProcessingInstruction) xpathnode).getNodeValue();
}
return null;
}
static public String getStringValue(Element el, boolean trimWhitespace) {
StringBuilder sb = new StringBuilder(1024);
String str;
NodeList nl = el.getChildNodes();
for (int i = 0; i < nl.getLength(); ++i) {
Node n = nl.item(i);
if (n instanceof Text) {
sb.append(n.getNodeValue());
}
}
if (trimWhitespace) {
str = sb.toString().trim();
} else {
str = sb.toString();
}
return str;
}
/**
* Receive notification of character data.
*
* <p>The Parser will call this method to report each chunk of
* character data. SAX parsers may return all contiguous character
* data in a single chunk, or they may split it into several
* chunks; however, all of the characters in any single event
* must come from the same external entity, so that the Locator
* provides useful information.</p>
*
* <p>The application must not attempt to read from the array
* outside of the specified range.</p>
*
* <p>Note that some parsers will report whitespace using the
* ignorableWhitespace() method rather than this one (validating
* parsers must do so).</p>
*
* @param ch The characters from the XML document.
* @param start The start position in the array.
* @param length The number of characters to read from the array.
* @see #ignorableWhitespace
* @see org.xml.sax.Locator
*/
public void characters(char ch[], int start, int length) throws org.xml.sax.SAXException
{
if(isOutsideDocElem()
&& XMLCharacterRecognizer.isWhiteSpace(ch, start, length))
return; // avoid DOM006 Hierarchy request error
if (m_inCData)
{
cdata(ch, start, length);
return;
}
String s = new String(ch, start, length);
Node childNode;
childNode = m_currentNode != null ? m_currentNode.getLastChild(): null;
if( childNode != null && childNode.getNodeType() == Node.TEXT_NODE ){
((Text)childNode).appendData(s);
}
else{
Text text = m_doc.createTextNode(s);
append(text);
}
}
/**
* Update the param-value node of the context-param entry. Don't add it if it already exists.
*
* @param doc
* @param children
* @param childNode
*/
@Override
protected void updateParamValue(Document doc, Node contextParamElement) {
NodeList valueChildren = contextParamElement.getChildNodes();
boolean foundEntry = false;
for (int i = 0; i < valueChildren.getLength() && !foundEntry; i++) {
Node valueChild = valueChildren.item(i);
if (valueChild instanceof Text) {
String value = valueChild.getNodeValue();
int index = value.indexOf(applicationContextPath);
if (index >= 0) {
System.out.println("Application context entry " + getApplicationContextPathWithClasspath()
+ " already in document.");
foundEntry = true;
}
}
}
if (!foundEntry) {
System.out.println("Adding " + getApplicationContextPathWithClasspath() + " to context");
contextParamElement.appendChild(doc.createTextNode(" " + getApplicationContextPathWithClasspath() + "\n"));
}
}
/**
* Recursively remove text nodes containing white spaces
*/
private void removeWhistespacesTextNodes(Node node) {
if (null == node) {
return;
}
NodeList list = node.getChildNodes();
for (int i = 0; i < list.getLength(); i++) {
Node child = list.item(i);
if (Node.TEXT_NODE == child.getNodeType()) {
Text text = (Text) child;
// if(text.isElementContentWhitespace())
{
node.removeChild(child);
i--;
}
} else if (Node.ELEMENT_NODE == child.getNodeType()) {
removeWhistespacesTextNodes(child);
}
}
}
private void writeXmlValue(final Node node) throws IOException {
Text firstChild = getFirstChildText(node);
String childNodeText = firstChild != null ? firstChild.getWholeText() : "";
childNodeText = childNodeText != null ? childNodeText.trim() : "";
if (NUMBER_PATTERN.matcher(childNodeText).matches()) {
writer.value(parseNumber(childNodeText));
return;
}
switch (childNodeText) {
case "null":
writer.nullValue();
break;
case "false":
writer.value(false);
break;
case "true":
writer.value(true);
break;
default:
writer.value(childNodeText);
}
}
/**
* Method engineAddContextToElement
*
* @param element
*/
public void engineAddContextToElement(Element element) {
if (element == null) {
throw new IllegalArgumentException("null element");
}
if (this.HMACOutputLengthSet) {
Document doc = element.getOwnerDocument();
Element HMElem =
XMLUtils.createElementInSignatureSpace(doc, Constants._TAG_HMACOUTPUTLENGTH);
Text HMText =
doc.createTextNode(Integer.valueOf(this.HMACOutputLength).toString());
HMElem.appendChild(HMText);
XMLUtils.addReturnToElement(element);
element.appendChild(HMElem);
XMLUtils.addReturnToElement(element);
}
}
private byte[] getElBytes(Element el, String childName) {
try {
Node kid = el.getFirstChild();
while (kid != null) {
if (childName.equals(kid.getNodeName())) {
Node nn = kid.getFirstChild();
if (nn instanceof Text) {
String dt = ((Text) nn).getData();
return Base64.decode(dt, Base64.DEFAULT);
}
}
kid = kid.getNextSibling();
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
* Base64 encodes and sets the bytes as the content of the SignatureValue
* Node.
*
* @param bytes bytes to be used by SignatureValue before Base64 encoding
*/
private void setSignatureValueElement(byte[] bytes) {
while (signatureValueElement.hasChildNodes()) {
signatureValueElement.removeChild(signatureValueElement.getFirstChild());
}
String base64codedValue = Base64.encode(bytes);
if (base64codedValue.length() > 76 && !XMLUtils.ignoreLineBreaks()) {
base64codedValue = "\n" + base64codedValue + "\n";
}
Text t = this.doc.createTextNode(base64codedValue);
signatureValueElement.appendChild(t);
}
/**
* Method decode
*
* Takes the <CODE>Text</CODE> children of the Element and interprets
* them as input for the <CODE>Base64.decode()</CODE> function.
*
* @param element
* @return the byte obtained of the decoding the element
* $todo$ not tested yet
* @throws Base64DecodingException
*/
public static final byte[] decode(Element element) throws Base64DecodingException {
Node sibling = element.getFirstChild();
StringBuffer sb = new StringBuffer();
while (sibling != null) {
if (sibling.getNodeType() == Node.TEXT_NODE) {
Text t = (Text) sibling;
sb.append(t.getData());
}
sibling = sibling.getNextSibling();
}
return decode(sb.toString());
}
/**
* Base64 encodes and sets the bytes as the content of the SignatureValue
* Node.
*
* @param bytes bytes to be used by SignatureValue before Base64 encoding
*/
private void setSignatureValueElement(byte[] bytes) {
while (signatureValueElement.hasChildNodes()) {
signatureValueElement.removeChild(signatureValueElement.getFirstChild());
}
String base64codedValue = Base64.encode(bytes);
if (base64codedValue.length() > 76 && !XMLUtils.ignoreLineBreaks()) {
base64codedValue = "\n" + base64codedValue + "\n";
}
Text t = this.doc.createTextNode(base64codedValue);
signatureValueElement.appendChild(t);
}
public void print(Node node) throws XMLStreamException {
switch (node.getNodeType()) {
case Node.DOCUMENT_NODE:
visitDocument((Document) node);
break;
case Node.DOCUMENT_FRAGMENT_NODE:
visitDocumentFragment((DocumentFragment) node);
break;
case Node.ELEMENT_NODE:
visitElement((Element) node);
break;
case Node.TEXT_NODE:
visitText((Text) node);
break;
case Node.CDATA_SECTION_NODE:
visitCDATASection((CDATASection) node);
break;
case Node.PROCESSING_INSTRUCTION_NODE:
visitProcessingInstruction((ProcessingInstruction) node);
break;
case Node.ENTITY_REFERENCE_NODE:
visitReference((EntityReference) node);
break;
case Node.COMMENT_NODE:
visitComment((Comment) node);
break;
case Node.DOCUMENT_TYPE_NODE:
break;
case Node.ATTRIBUTE_NODE:
case Node.ENTITY_NODE:
default:
throw new XMLStreamException("Unexpected DOM Node Type "
+ node.getNodeType()
);
}
}
/**
* Returns the unprocessed, unescaped, raw inner text of the receiver. Dies if
* the receiver has non-text children.
* <p>
* You probably want to use
* {@link #consumeInnerTextEscapedAsHtmlStringLiteral} instead.
*
* @return the text
* @throws UnableToCompleteException if it held anything other than text nodes
*/
public String consumeUnescapedInnerText() throws UnableToCompleteException {
final NodeList children = elem.getChildNodes();
if (children.getLength() < 1) {
return "";
}
if (children.getLength() > 1 || Node.TEXT_NODE != children.item(0).getNodeType()) {
logger.die(this, "Element must contain only text");
}
Text t = (Text) children.item(0);
return t.getTextContent();
}
void traverseElement(org.w3c.dom.Element node, StringBuilder sb) {
Node sibling = node.getFirstChild();
while (sibling != null) {
switch (sibling.getNodeType()) {
case Node.ELEMENT_NODE:
traverseElement((Element)sibling, sb);
break;
case Node.TEXT_NODE:
sb.append(((Text)sibling).getData());
}
sibling = sibling.getNextSibling();
}
}
/**
* Optimized dispatch of characters.
*/
private final void dispatachChars(Node node)
throws org.xml.sax.SAXException {
if (fSerializer != null) {
String data = ((Text) node).getData();
this.fSerializer.characters(data.toCharArray(), 0, data.length());
}
}
/**
* Sets the TEXT value of the <CODE>ds:XPath</CODE> Element.
*
* @param xpath
*/
public void setXPath(String xpath) {
if (this.constructionElement.getChildNodes() != null) {
NodeList nl = this.constructionElement.getChildNodes();
for (int i = 0; i < nl.getLength(); i++) {
this.constructionElement.removeChild(nl.item(i));
}
}
Text xpathText = this.doc.createTextNode(xpath);
this.constructionElement.appendChild(xpathText);
}
/**
* Extract nested text from an element.
* Currently does not handle coalescing text nodes, CDATA sections, etc.
* @param parent a parent element
* @return the nested text, or null if none was found
*/
static String findText(Element parent) {
NodeList l = parent.getChildNodes();
for (int i = 0; i < l.getLength(); i++) {
if (l.item(i).getNodeType() == Node.TEXT_NODE) {
Text text = (Text)l.item(i);
return text.getNodeValue();
}
}
return null;
}
/**
* Compares the two given nodes. This method delegates to one of the given methods depending
* on the expected node type:
*
* <ul>
* <li>{@link #compareCDATASectionNode(CDATASection, Node)}</li>
* <li>{@link #compareTextNode(Text, Node)}</li>
* <li>{@link #compareCommentNode(Comment, Node)}</li>
* <li>{@link #compareProcessingInstructionNode(ProcessingInstruction, Node)}</li>
* <li>For all other types, {@link #compareNames(Node, Node)} and
* {@link #compareAttributes(Node, Node)}</li>
* </ul>
*
* Then this method invokes itself recursively for every children,
* by a call to {@link #compareChildren(Node, Node)}.
*
* @param expected the expected node.
* @param actual the node to compare.
*/
protected void compareNode(final Node expected, final Node actual) {
if (expected == null || actual == null) {
fail(formatErrorMessage(expected, actual));
return;
}
/*
* Check text value for types:
* TEXT_NODE, CDATA_SECTION_NODE, COMMENT_NODE, PROCESSING_INSTRUCTION_NODE
*/
if (expected instanceof CDATASection) {
compareCDATASectionNode((CDATASection) expected, actual);
} else if (expected instanceof Text) {
compareTextNode((Text) expected, actual);
} else if (expected instanceof Comment) {
compareCommentNode((Comment) expected, actual);
} else if (expected instanceof ProcessingInstruction) {
compareProcessingInstructionNode((ProcessingInstruction) expected, actual);
} else if (expected instanceof Attr) {
compareAttributeNode((Attr) expected, actual);
} else {
compareNames(expected, actual);
compareAttributes(expected, actual);
}
/*
* Check child nodes recursivly if it's not an attribute.
*/
if (expected.getNodeType() != Node.ATTRIBUTE_NODE) {
compareChildren(expected, actual);
}
}
public Text addTextChild(Element targetElem, String value) {
if(value == null) {
return null;
}
Text newChild = targetElem.getOwnerDocument().createTextNode(value);
targetElem.appendChild(newChild);
return newChild;
}
@Override
public void characters(char[] ch, int start, int length) {
String data = new String(ch, start, length);
Node parent = getParent();
Node lastChild = parent.getLastChild();
if (lastChild != null && lastChild.getNodeType() == Node.TEXT_NODE) {
((Text) lastChild).appendData(data);
}
else {
Text text = this.document.createTextNode(data);
parent.appendChild(text);
}
}
/**
* Method getFullTextChildrenFromElement
*
* @param element
* @return the string of children
*/
public static String getFullTextChildrenFromElement(Element element) {
StringBuilder sb = new StringBuilder();
Node child = element.getFirstChild();
while (child != null) {
if (child.getNodeType() == Node.TEXT_NODE) {
sb.append(((Text)child).getData());
}
child = child.getNextSibling();
}
return sb.toString();
}
/**
* @param sibling
* @param uri
* @param nodeName
* @param number
* @return nodes with the constrain
*/
public static Text selectNodeText(Node sibling, String uri, String nodeName, int number) {
Node n = selectNode(sibling,uri,nodeName,number);
if (n == null) {
return null;
}
n = n.getFirstChild();
while (n != null && n.getNodeType() != Node.TEXT_NODE) {
n = n.getNextSibling();
}
return (Text)n;
}
public final Text splitText(int offset) throws DOMException {
Text newText = document.createTextNode(
substringData(offset, getLength() - offset));
deleteData(0, offset);
Node refNode = getNextSibling();
if (refNode == null) {
getParentNode().appendChild(newText);
} else {
getParentNode().insertBefore(newText, refNode);
}
return this;
}
public void setText( String text ) {
Text newChild = getOwnerDocument().createTextNode( text );
Text oldChild = getContentNode();
if (oldChild == null) {
appendChild( newChild );
} else {
replaceChild( newChild, oldChild );
}
}