Skip to Content.
Sympa Menu

xom-interest - Re: [XOM-interest] XOM 1.1: XPath

xom-interest AT lists.ibiblio.org

Subject: XOM API for Processing XML with Java

List archive

Chronological Thread  
  • From: Wolfgang Hoschek <whoschek AT lbl.gov>
  • To: Wolfgang Hoschek <whoschek AT lbl.gov>
  • Cc: Elliotte Harold <elharo AT metalab.unc.edu>, "Bradley S. Huffman" <hip AT a.cs.okstate.edu>, xom-interest AT lists.ibiblio.org
  • Subject: Re: [XOM-interest] XOM 1.1: XPath
  • Date: Sat, 8 Jan 2005 00:12:27 -0800

Thus, I continue to think that an explicit ParentNode.normalizeTexts() is the best way, if any. This approach is easy to understand, works, and few real use cases needs the text merging functionality anyway.

For example like this:

/**
* Walks the given node subtree and merges runs of adjacent (i.e. consecutive) {@link Text}
* nodes (if any) into a single Text node containing their string concatenation.
* This can sometimes be useful for XPath semantics.
* <p>
* Example:
* <pre>
* Element elem = new Element("elem");
* elem.appendChild("hello");
* elem.appendChild("world");
* elem.appendChild(new Element("bar"));
* elem.appendChild("nux");
*
* XOMUtil.normalizeTexts(elem);
*
* for (int i = 0; i &lt; elem.getChildCount(); i++) {
* System.out.println(elem.getChild(i).toString());
* }
* </pre>
*
* yields the following output:
*
* <pre>
* [nu.xom.Text: helloworld]
* [nu.xom.Element: bar]
* [nu.xom.Text: nux]
* </pre>
*
* @param node
* the subtree to normalize
*/
public static void normalizeTexts(ParentNode node) {
for (int i=node.getChildCount(); --i >= 0; ) {
Node child = node.getChild(i--);
if (i >= 0 && child instanceof Text) {
// scan to beginning of adjacent run, if any
int j = i+1;
while (i >= 0 && node.getChild(i) instanceof
Text) {
i--;
}

// found more than one adjacent Text node? if
so merge them
if (j-i > 1) {
StringBuffer buf = new StringBuffer();
// append forwards and remove backwards to minimize memory copies of list elems
i++;
int k = i;
while (k <= j)
buf.append(node.getChild(k++).getValue());
k = j;
while (k >= i) node.removeChild(k--);

// replace with merged Text node
node.insertChild(new
Text(buf.toString()), i);
}
}
else if (child instanceof Element) { // recursively
walk the tree
normalizeTexts((Element)child);
}
}
}


Wolfgang.





Archive powered by MHonArc 2.6.24.

Top of Page