Java Code Examples for org.w3c.dom.Text

The following code examples are extracted from open source projects. You can click to vote up the examples that are useful to you.

Example 1

From project apb, under directory /modules/apb-base/src/apb/utils/.

Source file: XmlUtils.java

  22 
vote

public static void addValuedElement(Document document,Element parent,String elementName,String content){
  Element name=document.createElement(elementName);
  Text text=document.createTextNode(content);
  name.appendChild(text);
  parent.appendChild(name);
}
 

Example 2

From project bpelunit, under directory /net.bpelunit.framework.control.deploy.activevos9/src/main/java/net/bpelunit/framework/model/bpel/.

Source file: TimingActivityHelper.java

  22 
vote

public void setFor(Element activity,String durationExpression){
  List<Element> timeExpressions=XMLUtil.getChildElementsByName(activity,ACTIVITY_OPTION_FOR);
  timeExpressions.addAll(XMLUtil.getChildElementsByName(activity,ACTIVITY_OPTION_UNTIL));
  Document document=activity.getOwnerDocument();
  Element newFor=document.createElementNS(activity.getNamespaceURI(),ACTIVITY_OPTION_FOR);
  Text newDuration=document.createTextNode(durationExpression);
  newFor.appendChild(newDuration);
  if (timeExpressions.size() > 0) {
    activity.replaceChild(newFor,timeExpressions.get(0));
  }
 else {
    XMLUtil.addAsFirstChild(activity,newFor);
  }
}
 

Example 3

From project echo2, under directory /src/app/java/nextapp/echo2/app/util/.

Source file: DomUtil.java

  22 
vote

/** 
 * Returns the text content of a DOM <code>Element</code>.
 * @param element The <code>Element</code> to analyze.
 */
public static String getElementText(Element element){
  NodeList children=element.getChildNodes();
  int childCount=children.getLength();
  for (int index=0; index < childCount; ++index) {
    if (children.item(index) instanceof Text) {
      Text text=(Text)children.item(index);
      return text.getData();
    }
  }
  return null;
}
 

Example 4

From project echo3, under directory /src/server-java/app/nextapp/echo/app/util/.

Source file: DomUtil.java

  22 
vote

/** 
 * Returns the text content of a DOM <code>Element</code>.
 * @param element The <code>Element</code> to analyze.
 */
public static String getElementText(Element element){
  NodeList children=element.getChildNodes();
  int childCount=children.getLength();
  for (int index=0; index < childCount; ++index) {
    if (children.item(index) instanceof Text) {
      Text text=(Text)children.item(index);
      return text.getData();
    }
  }
  return null;
}
 

Example 5

From project flyingsaucer, under directory /flying-saucer-core/src/main/java/org/xhtmlrenderer/simple/extend/.

Source file: XhtmlCssOnlyNamespaceHandler.java

  22 
vote

private static String readTextContent(Element element){
  StringBuffer result=new StringBuffer();
  Node current=element.getFirstChild();
  while (current != null) {
    short nodeType=current.getNodeType();
    if (nodeType == Node.TEXT_NODE || nodeType == Node.CDATA_SECTION_NODE) {
      Text t=(Text)current;
      result.append(t.getData());
    }
    current=current.getNextSibling();
  }
  return result.toString();
}
 

Example 6

From project lenya, under directory /org.apache.lenya.core.impl/src/main/java/org/apache/lenya/xml/.

Source file: NamespaceHelper.java

  22 
vote

/** 
 * <p> Creates an element within the namespace of this NamespaceHelper object with a given local name containing a text node. </p> <p> <code>createElement("text", "Hello World!")</code>: <code>&lt;prefix:text&gt;Hello World!&lt;/prefix:text&gt;</code>. </p>
 * @param localName The local name of the element.
 * @param text The text for the text node inside the element.
 * @return A new element containing a text node.
 */
public Element createElement(String localName,String text){
  Element element=createElement(localName);
  Text textNode=getDocument().createTextNode(text);
  element.appendChild(textNode);
  return element;
}
 

Example 7

From project lib-gwt-svg, under directory /src/main/java/com/google/gwt/uibinder/rebind/.

Source file: XMLElement.java

  22 
vote

/** 
 * 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();
}
 

Example 8

From project m2e-core-tests, under directory /org.eclipse.m2e.editor.xml.tests/src/org/eclipse/m2e/editor/xml/.

Source file: PomTemplateContextTest.java

  22 
vote

private Element addNode(Element parent,String childName,String childValue){
  Element child=addNode(parent,childName);
  Text text=parent.getOwnerDocument().createTextNode(childValue);
  child.appendChild(text);
  return child;
}
 

Example 9

From project Mockey, under directory /src/java/com/mockey/storage/xml/.

Source file: XMLGeneratorSupport.java

  22 
vote

/** 
 * Sets the given element text to be specified to text.
 * @param document the parent document used to create a text node.
 * @param element the element containing the text to set
 * @param text the text to be contained in the element; if <code>null</code>, then no text is provided.
 */
public void setText(Document document,Element element,String text){
  if (text != null) {
    Text textNode=document.createTextNode(text);
    element.appendChild(textNode);
  }
}
 

Example 10

From project nuxeo-tycho-osgi, under directory /nuxeo-common/src/main/java/org/nuxeo/common/persistence/.

Source file: XMLMemento.java

  22 
vote

public String getTextData(){
  Text textNode=getTextNode();
  if (textNode != null) {
    return textNode.getData();
  }
  return null;
}
 

Example 11

From project open-data-node, under directory /src/main/java/sk/opendata/odn/serialization/rdf/.

Source file: AbstractRdfSerializer.java

  22 
vote

protected Element appendTextNode(Document doc,String name,String value){
  Element element=doc.createElement(name);
  Text textNode=doc.createTextNode(value);
  element.appendChild(textNode);
  return element;
}
 

Example 12

From project riftsaw-ode, under directory /bpel-runtime/src/main/java/org/apache/ode/bpel/engine/.

Source file: BpelProcess.java

  22 
vote

public String getProcessProperty(QName property,String defaultValue){
  Text text=(Text)getProcessProperty(property);
  if (text == null) {
    return defaultValue;
  }
  String value=text.getWholeText();
  return (value == null) ? defaultValue : value;
}
 

Example 13

From project tesb-rt-se, under directory /locator/src/test/java/org/talend/esb/.

Source file: DomMother.java

  22 
vote

public static Text addText(Element parent,String text){
  Document doc=parent.getOwnerDocument();
  Text textNode=doc.createTextNode(text);
  parent.appendChild(textNode);
  return textNode;
}
 

Example 14

From project Weave, under directory /WeaveServices/src/weave/utils/.

Source file: XMLUtils.java

  22 
vote

public static Node appendTextNode(Node parent,String child){
  if (parent == null)   System.out.println("parent null 0");
  if (parent instanceof Document)   parent=((Document)parent).getDocumentElement();
  if (parent == null)   System.out.println("parent null 1");
  if (parent.getOwnerDocument() == null)   System.out.println("parent ownerdoc null");
  if (child == null)   System.out.println("child null");
  Text newNode=parent.getOwnerDocument().createTextNode(child);
  return parent.appendChild(newNode);
}
 

Example 15

From project xwiki-commons, under directory /xwiki-commons-core/xwiki-commons-xml/src/main/java/org/xwiki/xml/internal/html/filter/.

Source file: BodyFilter.java

  22 
vote

/** 
 * @param currentNode the current node to check
 * @return false if the current node contains something other than whitespaces or newlines, true otherwise
 */
private boolean containsOnlySpaces(Node currentNode){
  boolean result=true;
  if (currentNode.getNodeType() == Node.TEXT_NODE) {
    Text textNode=(Text)currentNode;
    if (textNode.getNodeValue().trim().length() > 0) {
      result=false;
    }
  }
 else   if (currentNode.getNodeType() != Node.COMMENT_NODE) {
    result=false;
  }
  return result;
}
 

Example 16

From project Cafe, under directory /webapp/src/org/openqa/selenium/os/.

Source file: WindowsUtils.java

  21 
vote

/** 
 * Returns a map of process IDs to command lines
 * @return a map of process IDs to command lines
 * @throws Exception - if something goes wrong while reading the process list
 */
public static Map procMap() throws Exception {
  log.info("Reading Windows Process List...");
  String output=executeCommand(findWMIC(),"process","list","full","/format:rawxml.xsl");
  log.info("Done, searching for processes to kill...");
  File TempWmicBatchFile=new File("TempWmicBatchFile.bat");
  if (TempWmicBatchFile.exists()) {
    TempWmicBatchFile.delete();
  }
  Document doc=DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(new ByteArrayInputStream(output.getBytes()));
  NodeList procList=doc.getElementsByTagName("INSTANCE");
  Map<String,String> processes=new HashMap<String,String>();
  for (int i=0; i < procList.getLength(); i++) {
    Element process=(Element)procList.item(i);
    NodeList propList=process.getElementsByTagName("PROPERTY");
    Map<String,Object> procProps=new HashMap<String,Object>();
    for (int j=0; j < propList.getLength(); j++) {
      Element property=(Element)propList.item(j);
      String propName=property.getAttribute("NAME");
      NodeList valList=property.getElementsByTagName("VALUE");
      String value=null;
      if (valList.getLength() != 0) {
        Element valueElement=(Element)valList.item(0);
        Text valueNode=(Text)valueElement.getFirstChild();
        value=valueNode.getData();
      }
      procProps.put(propName,value);
    }
    String processID=(String)procProps.get("ProcessId");
    String commandLine=(String)procProps.get("CommandLine");
    processes.put(commandLine,processID);
  }
  return processes;
}
 

Example 17

From project dozer, under directory /eclipse-plugin/net.sf.dozer.eclipse.plugin/src/org/dozer/eclipse/plugin/sourcepage/util/.

Source file: DozerPluginUtils.java

  21 
vote

public static String getMappingClassName(Node aOrBNode){
  if (!"a".equals(aOrBNode.getNodeName()) && !"b".equals(aOrBNode.getNodeName()))   return null;
  String aOrBNodeName=aOrBNode.getNodeName();
  Node mappingNode=getMappingNode(aOrBNode);
  NodeList childNodes=mappingNode.getChildNodes();
  int len=childNodes.getLength();
  for (int i=0; i < len; i++) {
    Node childNode=childNodes.item(i);
    if (childNode.getNodeType() == Node.ELEMENT_NODE && childNode.getNodeName().equals("class-" + aOrBNodeName)) {
      Text textNode=(Text)childNode.getFirstChild();
      return textNode.getNodeValue();
    }
  }
  return null;
}
 

Example 18

From project fitnesse, under directory /src/fitnesse/responders/run/.

Source file: ExecutionReportTest.java

  21 
vote

@Test public void shouldHandleMissingRunTimesGraceFully() throws Exception {
  TestExecutionReport report=new TestExecutionReport();
  Element element=mock(Element.class);
  NodeList emptyNodeList=mock(NodeList.class);
  when(element.getElementsByTagName("totalRunTimeInMillis")).thenReturn(emptyNodeList);
  when(emptyNodeList.getLength()).thenReturn(0);
  assertThat(report.getTotalRunTimeInMillisOrZeroIfNotPresent(element),is(0L));
  element=mock(Element.class);
  NodeList matchingNodeList=mock(NodeList.class);
  Node elementWithText=mock(Element.class);
  NodeList childNodeList=mock(NodeList.class);
  Text text=mock(Text.class);
  when(element.getElementsByTagName("totalRunTimeInMillis")).thenReturn(matchingNodeList);
  when(matchingNodeList.getLength()).thenReturn(1);
  when(matchingNodeList.item(0)).thenReturn(elementWithText);
  when(elementWithText.getChildNodes()).thenReturn(childNodeList);
  when(childNodeList.getLength()).thenReturn(1);
  when(childNodeList.item(0)).thenReturn(text);
  when(text.getNodeValue()).thenReturn("255");
  assertThat(report.getTotalRunTimeInMillisOrZeroIfNotPresent(element),is(255L));
}
 

Example 19

From project gda-common, under directory /uk.ac.gda.common/src/gda/configuration/properties/.

Source file: PropertiesToXmlConverter.java

  21 
vote

/** 
 * Create a XML DOM representation for a property key-value pair (from a Properties object). N.B. Should create a representation compatible with Jakarta commons configuration XML properties file format.
 * @param root the root element of the DOM instance
 * @param propertyName name of a property
 * @param propertyValue value of the property
 */
private void addPropertyToXmlDomRepresentation(Element root,String propertyName,String propertyValue){
  int split;
  String name=propertyName;
  Element current=root;
  Element test=null;
  while ((split=name.indexOf(".")) != -1) {
    String subName=name.substring(0,split);
    name=name.substring(split + 1);
    if ((test=getChild(current,subName)) == null) {
      Element subElement=doc.createElement(subName);
      addChildSortedAlphabetically(current,subElement);
      current=subElement;
    }
 else {
      current=test;
    }
  }
  char c=name.charAt(0);
  if (Character.isLetter(c) == false) {
    logger.debug("Found non-alpha first-character in last segment of property: " + propertyName + " ("+ name+ ")");
    logger.debug("Converting to: " + prependString + name);
    logger.debug("");
    name=prependString + name;
  }
  Element last=null;
  Text valueTextNode=null;
  try {
    last=doc.createElement(name);
    valueTextNode=doc.createTextNode(propertyValue);
    last.appendChild(valueTextNode);
    addChildSortedAlphabetically(current,last);
  }
 catch (  DOMException e) {
    logger.error(e.getMessage());
  }
}
 

Example 20

From project hudson-test-harness, under directory /src/test/java/hudson/model/.

Source file: ViewTest.java

  21 
vote

public void testPrivateView() throws Exception {
  createFreeStyleProject("project1");
  User user=User.get("me",true);
  WebClient wc=new WebClient();
  HtmlPage userPage=wc.goTo("/user/me");
  HtmlAnchor privateViewsLink=userPage.getFirstAnchorByText("My Views");
  assertNotNull("My Views link not available",privateViewsLink);
  HtmlPage privateViewsPage=(HtmlPage)privateViewsLink.click();
  Text viewLabel=(Text)privateViewsPage.getFirstByXPath("//table[@id='viewList']//td[@class='active']/text()");
  assertTrue("'All' view should be selected",viewLabel.getTextContent().contains(Hudson_ViewName()));
  View listView=new ListView("listView",hudson);
  hudson.addView(listView);
  HtmlPage newViewPage=wc.goTo("/user/me/my-views/newView");
  HtmlForm form=newViewPage.getFormByName("createView");
  form.getInputByName("name").setValueAttribute("proxy-view");
  ((HtmlRadioButtonInput)form.getInputByValue("hudson.model.ProxyView")).setChecked(true);
  HtmlPage proxyViewConfigurePage=submit(form);
  View proxyView=user.getProperty(MyViewsProperty.class).getView("proxy-view");
  assertNotNull(proxyView);
  form=proxyViewConfigurePage.getFormByName("viewConfig");
  form.getSelectByName("proxiedViewName").setSelectedAttribute("listView",true);
  submit(form);
  assertTrue(proxyView instanceof ProxyView);
  assertEquals(((ProxyView)proxyView).getProxiedViewName(),"listView");
  assertEquals(((ProxyView)proxyView).getProxiedView(),listView);
}
 

Example 21

From project Kairos, under directory /src/plugin/parse-html/src/java/org/apache/nutch/parse/html/.

Source file: DOMBuilder.java

  21 
vote

/** 
 * 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;
  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);
  }
}
 

Example 22

From project keepassdroid, under directory /src/com/keepassdroid/database/.

Source file: PwDatabaseV4.java

  21 
vote

@Override protected byte[] loadXmlKeyFile(String fileName){
  try {
    DocumentBuilderFactory dbf=DocumentBuilderFactory.newInstance();
    DocumentBuilder db=dbf.newDocumentBuilder();
    FileInputStream fis=new FileInputStream(fileName);
    Document doc=db.parse(fis);
    Element el=doc.getDocumentElement();
    if (el == null || !el.getNodeName().equalsIgnoreCase(RootElementName)) {
      return null;
    }
    NodeList children=el.getChildNodes();
    if (children.getLength() < 2) {
      return null;
    }
    for (int i=0; i < children.getLength(); i++) {
      Node child=children.item(i);
      if (child.getNodeName().equalsIgnoreCase(KeyElementName)) {
        NodeList keyChildren=child.getChildNodes();
        for (int j=0; j < keyChildren.getLength(); j++) {
          Node keyChild=keyChildren.item(j);
          if (keyChild.getNodeName().equalsIgnoreCase(KeyDataElementName)) {
            NodeList children2=keyChild.getChildNodes();
            for (int k=0; k < children2.getLength(); k++) {
              Node text=children2.item(k);
              if (text.getNodeType() == Node.TEXT_NODE) {
                Text txt=(Text)text;
                return Base64Coder.decode(txt.getNodeValue());
              }
            }
          }
        }
      }
    }
  }
 catch (  Exception e) {
    return null;
  }
  return null;
}
 

Example 23

From project litle-sdk-for-java, under directory /lib/apache-cxf-2.5.2/samples/aegis/src/main/java/demo/hw/client/.

Source file: Client.java

  21 
vote

public static void main(String args[]) throws Exception {
  ClientProxyFactoryBean factory=new ClientProxyFactoryBean();
  if (args != null && args.length > 0 && !"".equals(args[0])) {
    factory.setAddress(args[0]);
  }
 else {
    factory.setAddress("http://localhost:9000/Hello");
  }
  factory.getServiceFactory().setDataBinding(new AegisDatabinding());
  HelloWorld client=factory.create(HelloWorld.class);
  System.out.println("Invoke sayHi()....");
  System.out.println(client.sayHi(System.getProperty("user.name")));
  Document doc=client.getADocument();
  Element e=(Element)doc.getFirstChild();
  System.out.println(e.getTagName());
  Text t=(Text)e.getFirstChild();
  System.out.println(t);
}
 

Example 24

From project nutch, under directory /src/plugin/parse-html/src/java/org/apache/nutch/parse/html/.

Source file: DOMBuilder.java

  21 
vote

/** 
 * 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;
  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);
  }
}
 

Example 25

From project pegadi, under directory /storysketch/src/main/java/org/pegadi/storysketch/.

Source file: XMLUtil.java

  21 
vote

public static Element createParagraphElement(String name,String content,Document doc){
  Element element=doc.createElement(name);
  BufferedReader br=new BufferedReader(new StringReader(content));
  try {
    while (br.ready()) {
      String p=br.readLine();
      if (p == null)       break;
      Element pe=doc.createElement("p");
      Text t=doc.createTextNode(p);
      pe.appendChild(t);
      element.appendChild(pe);
    }
  }
 catch (  IOException ioe) {
    ioe.printStackTrace();
  }
  return element;
}
 

Example 26

From project rapid, under directory /rapid-generator/rapid-generator/src/main/java/cn/org/rapid_framework/generator/util/.

Source file: XMLHelper.java

  21 
vote

private static StringBuffer nodeAsText(Node elm,StringBuffer sb,boolean ignoreComments){
  if (elm.getNodeType() == Node.CDATA_SECTION_NODE) {
    CDATASection cdata=(CDATASection)elm;
    sb.append("<![CDATA[");
    sb.append(cdata.getData());
    sb.append("]]>");
    return sb;
  }
  if (elm.getNodeType() == Node.COMMENT_NODE) {
    if (ignoreComments) {
      return sb;
    }
    Comment c=(Comment)elm;
    sb.append("<!--");
    sb.append(c.getData());
    sb.append("-->");
    return sb;
  }
  if (elm.getNodeType() == Node.TEXT_NODE) {
    Text t=(Text)elm;
    sb.append(StringHelper.escapeXml(t.getData(),"<&"));
    return sb;
  }
  NodeList childs=elm.getChildNodes();
  sb.append("<" + elm.getNodeName());
  attributes2String(elm,sb);
  if (childs.getLength() > 0) {
    sb.append(">");
    for (int i=0; i < childs.getLength(); i++) {
      Node child=childs.item(i);
      nodeAsText(child,sb,ignoreComments);
    }
    sb.append("</" + elm.getNodeName() + ">");
  }
 else {
    sb.append("/>");
  }
  return sb;
}
 

Example 27

From project riftsaw, under directory /console/bpel2svg/src/main/java/org/wso2/carbon/bpel/ui/bpel2svg/impl/.

Source file: ActivityImpl.java

  21 
vote

protected Element getImageText(SVGDocument doc,int imgXLeft,int imgYTop,int imgWidth,int imgHeight,String imgName,String imgDisplayName){
  int txtXLeft=imgXLeft;
  int txtYTop=imgYTop;
  Element a=doc.createElementNS("http://www.w3.org/2000/svg","a");
  if (imgDisplayName != null) {
    a.setAttributeNS(null,"id",imgName);
    Element text1=doc.createElementNS("http://www.w3.org/2000/svg","text");
    text1.setAttributeNS(null,"x",String.valueOf(txtXLeft));
    text1.setAttributeNS(null,"y",String.valueOf(txtYTop));
    text1.setAttributeNS(null,"id",imgName + ".Text");
    text1.setAttributeNS(null,"xml:space","preserve");
    text1.setAttributeNS(null,"style","font-size:12px;font-style:normal;font-variant:normal;font-weight:" + "normal;font-stretch:normal;text-align:start;line-height:125%;writing-mode:lr-tb;text-anchor:" + "start;fill:#000000;fill-opacity:1;stroke:none;stroke-width:1px;stroke-linecap:butt;"+ "stroke-linejoin:miter;stroke-opacity:1;font-family:Arial Narrow;"+ "-inkscape-font-specification:Arial Narrow");
    Element tspan=doc.createElementNS("http://www.w3.org/2000/svg","tspan");
    tspan.setAttributeNS(null,"x",String.valueOf(txtXLeft));
    tspan.setAttributeNS(null,"y",String.valueOf(txtYTop));
    tspan.setAttributeNS(null,"id","tspan-" + imgName);
    Text text2=doc.createTextNode(imgDisplayName);
    tspan.appendChild(text2);
    text1.appendChild(tspan);
    a.appendChild(text1);
  }
  return a;
}
 

Example 28

From project servicemix-utils, under directory /src/test/java/org/apache/servicemix/jbi/jaxp/.

Source file: StaxSourceTest.java

  21 
vote

protected void checkDomResult(Document doc){
  NodeList l=doc.getElementsByTagName("child4");
  assertEquals(1,l.getLength());
  assertEquals(1,l.item(0).getChildNodes().getLength());
  Text txt=(Text)l.item(0).getFirstChild();
  assertEquals("   ",txt.getData());
  l=doc.getDocumentElement().getElementsByTagName("long");
  assertEquals(1,l.getLength());
  assertEquals(1,l.item(0).getChildNodes().getLength());
  txt=(Text)l.item(0).getFirstChild();
  StringBuffer expected=new StringBuffer();
  for (int i=0; i < 4; i++) {
    for (int j=0; j < 10; j++) {
      for (int k=0; k < 10; k++) {
        expected.append((char)('0' + j));
        expected.append((char)('0' + k));
        if (k != 9) {
          expected.append(' ');
        }
      }
      expected.append("\n");
    }
  }
  assertEquals(expected.toString(),txt.getData());
}
 

Example 29

From project spring-android, under directory /spring-android-rest-template-test/src/main/java/org/springframework/http/converter/xml/.

Source file: SourceHttpMessageConverterTests.java

  21 
vote

@SmallTest public void testWriteDOMSource() throws Exception {
  if (javaxXmlTransformPresent) {
    DocumentBuilderFactory documentBuilderFactory=DocumentBuilderFactory.newInstance();
    documentBuilderFactory.setNamespaceAware(true);
    Document document=documentBuilderFactory.newDocumentBuilder().newDocument();
    Element rootElement=document.createElement("root");
    document.appendChild(rootElement);
    Text text=document.createTextNode("Hello World");
    rootElement.appendChild(text);
    DOMSource domSource=new DOMSource(document);
    MockHttpOutputMessage outputMessage=new MockHttpOutputMessage();
    converter.write(domSource,null,outputMessage);
    String s=outputMessage.getBodyAsString(Charset.forName("UTF-8"));
    assertTrue("Invalid result",s.contains("<root>Hello World</root>"));
    assertEquals("Invalid content-type",new MediaType("application","xml"),outputMessage.getHeaders().getContentType());
    assertEquals("Invalid content-length",outputMessage.getBodyAsBytes().length,outputMessage.getHeaders().getContentLength());
  }
}
 

Example 30

From project utils_1, under directory /src/main/java/net/pterodactylus/util/xml/.

Source file: SimpleXML.java

  21 
vote

/** 
 * Appends all children of this node to the specified  {@link Element}. If a node has a value that is not <code>null</code> the value is appended as a text node.
 * @param rootElement The element to attach this node's children to
 */
private void addChildren(Element rootElement){
  for (  SimpleXML child : children) {
    Element childElement=rootElement.getOwnerDocument().createElement(child.name);
    for (    Entry<String,String> attributeEntry : child.attributes.entrySet()) {
      childElement.setAttribute(attributeEntry.getKey(),attributeEntry.getValue());
    }
    rootElement.appendChild(childElement);
    if (child.value != null) {
      Text childText=rootElement.getOwnerDocument().createTextNode(child.value);
      childElement.appendChild(childText);
    }
 else {
      child.addChildren(childElement);
    }
  }
}
 

Example 31

From project wikbook, under directory /core/src/main/java/org/wikbook/core/xml/.

Source file: XML.java

  21 
vote

/** 
 * Cleanup the element from any white space children it may have.
 * @param elt the element to cleanup
 * @throws NullPointerException if the element is null
 */
public static void removeWhiteSpace(Element elt) throws NullPointerException {
  if (elt == null) {
    throw new NullPointerException();
  }
  List<Node> childrenToRemove=null;
  NodeList children=elt.getChildNodes();
  for (int i=0; i < children.getLength(); i++) {
    Node child=children.item(i);
    if (child instanceof Text) {
      Text textChild=(Text)child;
      String trimmed=textChild.getData().trim();
      if (trimmed.length() == 0) {
        if (childrenToRemove == null) {
          childrenToRemove=new LinkedList<Node>();
        }
        childrenToRemove.add(textChild);
      }
 else {
        textChild.setData(trimmed);
      }
    }
 else     if (child instanceof Element) {
      Element eltChild=(Element)child;
      removeWhiteSpace(eltChild);
    }
  }
  if (childrenToRemove != null) {
    for (    Node child : childrenToRemove) {
      elt.removeChild(child);
    }
  }
}
 

Example 32

From project zen-project, under directory /zen-base/src/main/java/com/nominanuda/xml/.

Source file: DOMBuilder.java

  21 
vote

/** 
 * 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() && saxHelper.isWhiteSpace(ch,start,length))   return;
  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);
  }
}
 

Example 33

From project adt-maven-plugin, under directory /src/test/java/com/yelbota/plugins/adt/model/.

Source file: ApplicationDescriptorModelTest.java

  19 
vote

private void testDomExtensions(Document doc,ApplicationDescriptorModel c) throws XPathExpressionException {
  XPathFactory factory=XPathFactory.newInstance();
  XPath xpath=factory.newXPath();
  Object result=xpath.compile("//extensions/extensionID/text()").evaluate(doc,XPathConstants.NODESET);
  if (result instanceof NodeList) {
    NodeList nodes=(NodeList)result;
    if (c.getExtensionIds() == null || c.getExtensionIds().size() < 1) {
      Assert.assertTrue(nodes.getLength() == 0);
    }
 else {
      List<String> modelExtensions=c.getExtensionIds();
      List<Text> filteredNodes=new ArrayList<Text>();
      for (int i=0; i < nodes.getLength(); i++) {
        Object node=nodes.item(i);
        if (node instanceof Text)         filteredNodes.add((Text)node);
      }
      if (modelExtensions.size() != filteredNodes.size()) {
        Assert.fail();
      }
 else {
        for (int i=0; i < filteredNodes.size(); i++) {
          String nodeContent=filteredNodes.get(i).getTextContent();
          String modelExtensionId=modelExtensions.get(i);
          Assert.assertEquals(nodeContent,modelExtensionId);
        }
      }
    }
  }
 else {
    Assert.fail("Extensions is not node list");
  }
}
 

Example 34

From project any23, under directory /core/src/main/java/org/apache/any23/extractor/html/.

Source file: HTMLDocument.java

  19 
vote

/** 
 * Returns the text contained inside a node if leaf, <code>null</code> otherwise.
 * @return the text of a leaf node.
 */
public String getText(){
  NodeList children=getDocument().getChildNodes();
  if (children.getLength() == 1 && children.item(0) instanceof Text) {
    return children.item(0).getTextContent();
  }
  return null;
}
 

Example 35

From project cdk, under directory /xinclude/src/main/java/org/apache/cocoon/pipeline/util/dom/.

Source file: DOMStreamer.java

  19 
vote

private void dispatchChars(Node node) throws SAXException {
  final String data=((Text)node).getData();
  if (data != null) {
    xmlConsumer.characters(data.toCharArray(),0,data.length());
  }
}
 

Example 36

From project core_1, under directory /config/src/main/java/org/switchyard/config/.

Source file: DOMConfiguration.java

  19 
vote

/** 
 * {@inheritDoc}
 */
@Override public String getValue(){
  Node text_node=getTextNode(false);
  if (text_node instanceof Text) {
    return ((Text)text_node).getWholeText();
  }
 else   if (text_node != null) {
    return text_node.getNodeValue();
  }
  return null;
}
 

Example 37

From project gatein-common, under directory /common/src/main/java/org/gatein/common/xml/.

Source file: XMLTools.java

  19 
vote

/** 
 * Get the element's content as a string.
 * @param element the container
 * @param trim    true if text should be trimmed before returning result
 * @throws IllegalArgumentException if the element content is mixed or null
 */
public static String asString(Element element,boolean trim) throws IllegalArgumentException {
  if (element == null) {
    throw new IllegalArgumentException("No null element allowed");
  }
  StringBuffer buffer=new StringBuffer();
  NodeList children=element.getChildNodes();
  for (int i=0; i < children.getLength(); i++) {
    Node child=children.item(i);
switch (child.getNodeType()) {
case Node.CDATA_SECTION_NODE:
case Node.TEXT_NODE:
      buffer.append(((Text)child).getData());
    break;
case Node.ELEMENT_NODE:
  throw new IllegalArgumentException("Mixed content not allowed");
default :
break;
}
}
String result=buffer.toString();
if (trim) {
result=result.trim();
}
return result;
}
 

Example 38

From project geronimo-xbean, under directory /xbean-spring/src/main/java/org/apache/xbean/spring/context/v2c/.

Source file: XBeanNamespaceHandler.java

  19 
vote

protected void addContentProperty(BeanDefinitionHolder definition,MappingMetaData metadata,Element element){
  String name=metadata.getContentProperty(getLocalName(element));
  if (name != null) {
    String value=getElementText(element);
    addProperty(definition,metadata,element,name,value);
  }
 else {
    StringBuffer buffer=new StringBuffer();
    NodeList childNodes=element.getChildNodes();
    for (int i=0, size=childNodes.getLength(); i < size; i++) {
      Node node=childNodes.item(i);
      if (node instanceof Text) {
        buffer.append(((Text)node).getData());
      }
    }
    ByteArrayInputStream in=new ByteArrayInputStream(buffer.toString().getBytes());
    Properties properties=new Properties();
    try {
      properties.load(in);
    }
 catch (    IOException e) {
      return;
    }
    Enumeration enumeration=properties.propertyNames();
    while (enumeration.hasMoreElements()) {
      String propertyName=(String)enumeration.nextElement();
      String propertyEditor=metadata.getPropertyEditor(getLocalName(element),propertyName);
      Object value=getValue(properties.getProperty(propertyName),propertyEditor);
      definition.getBeanDefinition().getPropertyValues().addPropertyValue(propertyName,value);
    }
  }
}
 

Example 39

From project gravitext, under directory /gravitext-xmlprod/src/main/java/com/gravitext/xml/producer/.

Source file: DOMWalker.java

  19 
vote

/** 
 * Writes the specified DOM node and its children to the producer by recursive descent. Only some node types are output: <ul> <li>Document and DocumentFragment nodes are only descended into.</li> <li>CDATASection and Text nodes are written identically via putChars.</li> <li>Element attributes are written in the order found, which is typically undefined/</li> <li>All other node types are ignored.</li> </ul> <p>Namespace information in the DOM is observed. For best results, enable Namespace processing when constructing the DOM.</p>
 */
public void putDOM(final Node node) throws IOException {
  if (node instanceof Element) {
    putElement(node);
  }
 else   if ((node instanceof Text) || (node instanceof CDATASection)) {
    _pd.putChars(node.getNodeValue());
  }
 else   if ((node instanceof Document) || (node instanceof DocumentFragment)) {
    putNodeList(node.getChildNodes());
  }
}
 

Example 40

From project hbasene, under directory /src/main/java/org/hbasene/index/create/.

Source file: IndexConfiguration.java

  19 
vote

private void propertyFromXML(Element prop,Properties properties){
  NodeList fields=prop.getChildNodes();
  String attr=null;
  String value=null;
  for (int j=0; j < fields.getLength(); j++) {
    Node fieldNode=fields.item(j);
    if (!(fieldNode instanceof Element)) {
      continue;
    }
    Element field=(Element)fieldNode;
    if ("name".equals(field.getTagName())) {
      attr=((Text)field.getFirstChild()).getData();
    }
    if ("value".equals(field.getTagName()) && field.hasChildNodes()) {
      value=((Text)field.getFirstChild()).getData();
    }
  }
  if (attr != null && value != null) {
    if (properties == null) {
      set(attr,value);
    }
 else {
      properties.setProperty(attr,value);
    }
  }
}
 

Example 41

From project jSCSI, under directory /bundles/target/src/main/java/org/jscsi/target/.

Source file: Configuration.java

  19 
vote

private static Node chopWhiteSpaces(final Node node){
  Node toIterate=node;
  while (toIterate instanceof Text && toIterate.getTextContent().trim().length() == 0) {
    toIterate=toIterate.getNextSibling();
  }
  return toIterate;
}
 

Example 42

From project jumpnevolve, under directory /lib/slick/src/org/newdawn/slick/util/xml/.

Source file: XMLElement.java

  19 
vote

/** 
 * Get the text content of the element, i.e. the bit between the tags
 * @return The text content of the node
 */
public String getContent(){
  String content="";
  NodeList list=dom.getChildNodes();
  for (int i=0; i < list.getLength(); i++) {
    if (list.item(i) instanceof Text) {
      content+=(list.item(i).getNodeValue());
    }
  }
  return content;
}
 

Example 43

From project liquibase, under directory /liquibase-core/src/main/java/liquibase/util/.

Source file: XMLUtil.java

  19 
vote

/** 
 * Extracts the text from the given element. Element.getTextContet() is java5 specific, so we need to use this until we drop 1.4 support.
 */
public static String getTextContent(Node element){
  StringBuffer text=new StringBuffer();
  NodeList childNodes=element.getChildNodes();
  for (int i=0; i < childNodes.getLength(); i++) {
    Node child=childNodes.item(i);
    if (child instanceof Text) {
      text.append(child.getNodeValue());
    }
  }
  return text.toString();
}
 

Example 44

From project moho, under directory /moho-common/src/main/java/com/voxeo/moho/common/util/.

Source file: XmlUtils.java

  19 
vote

public static String getElementContent(final Element element,final boolean trim){
  final NodeList nl=element.getChildNodes();
  String attributeText="";
  for (int i=0; i < nl.getLength(); i++) {
    final Node n=nl.item(i);
    if (n instanceof Text) {
      attributeText+=((Text)n).getData();
    }
  }
  if (trim) {
    attributeText=attributeText.trim();
  }
  return attributeText;
}
 

Example 45

From project OWASP-WebScarab, under directory /src/org/owasp/webscarab/util/.

Source file: DOMHandler.java

  19 
vote

public void characters(char[] ch,int start,int length){
  Node last=(Node)_stack.peek();
  if (last != _document) {
    final String text=new String(ch,start,length);
    if (_last != null && _last.getNodeType() == Node.TEXT_NODE) {
      ((Text)_last).appendData(text);
    }
 else {
      _last=last.appendChild(_document.createTextNode(text));
    }
  }
}
 

Example 46

From project PDF-to-unusual-HTML, under directory /PDF-to-unusual-HTML/src/org/apache/pdfbox/util/.

Source file: XMLUtil.java

  19 
vote

/** 
 * This will get the text value of an element.
 * @param node The node to get the text value for.
 * @return The text of the node.
 */
public static String getNodeValue(Element node){
  String retval="";
  NodeList children=node.getChildNodes();
  for (int i=0; i < children.getLength(); i++) {
    Node next=children.item(i);
    if (next instanceof Text) {
      retval=next.getNodeValue();
    }
  }
  return retval;
}
 

Example 47

From project picketlink-idm, under directory /picketlink-idm-testsuite/common/src/test/java/org/picketlink/idm/test/support/.

Source file: XMLTools.java

  19 
vote

/** 
 * Get the element's content as a string.
 * @param element the container
 * @param trim    true if text should be trimmed before returning result
 * @throws IllegalArgumentException if the element content is mixed or null
 */
public static String asString(Element element,boolean trim) throws IllegalArgumentException {
  if (element == null) {
    throw new IllegalArgumentException("No null element allowed");
  }
  StringBuffer buffer=new StringBuffer();
  NodeList children=element.getChildNodes();
  for (int i=0; i < children.getLength(); i++) {
    Node child=children.item(i);
switch (child.getNodeType()) {
case Node.CDATA_SECTION_NODE:
case Node.TEXT_NODE:
      buffer.append(((Text)child).getData());
    break;
case Node.ELEMENT_NODE:
  throw new IllegalArgumentException("Mixed content not allowed");
default :
break;
}
}
String result=buffer.toString();
if (trim) {
result=result.trim();
}
return result;
}
 

Example 48

From project polyglot-maven, under directory /pmaven-groovy/src/main/java/org/sonatype/maven/polyglot/groovy/.

Source file: Dom2Groovy.java

  19 
vote

protected void print(final Node node,final Map namespaces,final boolean endWithComma){
switch (node.getNodeType()) {
case Node.ELEMENT_NODE:
    printElement((Element)node,namespaces,endWithComma);
  break;
case Node.PROCESSING_INSTRUCTION_NODE:
printPI((ProcessingInstruction)node,endWithComma);
break;
case Node.TEXT_NODE:
printText((Text)node,endWithComma);
break;
case Node.COMMENT_NODE:
printComment((Comment)node,endWithComma);
break;
}
}
 

Example 49

From project SWOWS, under directory /swows/src/main/java/org/swows/xmlinrdf/.

Source file: DomDecoder.java

  19 
vote

private org.w3c.dom.Node decodeNode(Graph graph,Node elementNode){
  try {
    Node nodeType=graph.find(elementNode,XML.nodeType.asNode(),Node.ANY).next().getObject();
    if (nodeType.equals(XML.Attr.asNode()))     return decodeAttr(graph,elementNode);
    if (nodeType.equals(XML.Comment.asNode()))     return decodeComment(graph,elementNode);
    if (nodeType.equals(XML.Element.asNode()))     return decodeElement(graph,elementNode);
    if (nodeType.equals(XML.ProcessingInstruction.asNode()))     return decodeProcessingInstruction(graph,elementNode);
    if (nodeType.equals(XML.Text.asNode()))     return decodeText(graph,elementNode);
    throw new RuntimeException("Type not recognised for node " + elementNode);
  }
 catch (  NoSuchElementException e) {
    throw new RuntimeException("Type not found for node " + elementNode);
  }
}
 

Example 50

From project uomo, under directory /bundles/org.eclipse.uomo.xml/src/test/java/org/eclipse/uomo/xml/test/.

Source file: XMLTestCase.java

  19 
vote

private String compareElements(Element e1,Element e2,String p){
  if (!e1.getNamespaceURI().equals(e2.getNamespaceURI()))   return "element namespaces differ at " + p;
  if (!e1.getLocalName().equals(e2.getLocalName()))   return "element names differ at " + p;
  String msg=compareAttributes(e1,e2,p);
  if (msg != null)   return msg;
  p=p + "/" + e1.getNodeName();
  int i=0;
  Node c1=getNextRelevantNode(e1.getFirstChild());
  Node c2=getNextRelevantNode(e2.getFirstChild());
  while (c1 != null && c2 != null) {
    if (c1.getNodeType() != c2.getNodeType())     return "Different node types (" + Integer.toString(c1.getNodeType()) + "/"+ c2.getNodeType()+ ") @ "+ p;
    msg=null;
    if (c1.getNodeType() == Node.TEXT_NODE) {
      msg=compareTexts((Text)c1,(Text)c2,p + "[" + Integer.toString(i)+ "]");
    }
 else     if (c1.getNodeType() == Node.ELEMENT_NODE) {
      msg=compareElements((Element)c1,(Element)c2,p + "[" + Integer.toString(i)+ "]");
    }
 else     msg="unknown node type " + Integer.toString(c1.getNodeType());
    if (msg != null)     return msg;
    c1=getNextRelevantNode(c1.getNextSibling());
    c2=getNextRelevantNode(c2.getNextSibling());
    i++;
  }
  if (c1 != null && c2 == null)   return "node present in one and not in two @ " + p;
  if (c2 != null && c1 == null)   return "node present in two and not in one @ " + p;
  return null;
}
 

Example 51

From project Vega, under directory /platform/com.subgraph.vega.scanner.modules/src/com/subgraph/vega/impl/scanner/modules/scripting/dom/.

Source file: NodeJS.java

  19 
vote

private static NodeJS createNodeJSFromDomNode(Node node,DocumentJS document){
  if (node == null) {
    return null;
  }
 else   if (node instanceof HTMLElement) {
    return HTMLElementJS.domHTMLElementToJS((HTMLElement)node,document);
  }
 else   if (node instanceof HTMLDocument) {
    return document;
  }
 else   if (node instanceof Comment) {
    return new CommentJS((Comment)node,document);
  }
 else   if (node instanceof Text) {
    return new TextJS((Text)node,document);
  }
 else   if (node instanceof CharacterData) {
    return new CharacterDataJS((CharacterData)node,document);
  }
 else   if (node instanceof Attr) {
    return new AttrJS((Attr)node,document);
  }
 else   if (node instanceof Document) {
    return document;
  }
 else   if (node instanceof Element) {
    return new ElementJS((Element)node,document);
  }
 else {
    return new NodeJS(node,document);
  }
}