how to get a text's parent element in docx4j?
below is my code
- Code: Select all
package org;
import java.awt.Color;
import java.io.File;
import java.math.BigInteger;
import java.util.List;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBElement;
import org.docx4j.TraversalUtil;
import org.docx4j.XmlUtils;
import org.docx4j.TraversalUtil.Callback;
import org.docx4j.openpackaging.packages.WordprocessingMLPackage;
import org.docx4j.openpackaging.parts.WordprocessingML.MainDocumentPart;
import org.docx4j.wml.Body;
import org.docx4j.wml.RPr;
import org.docx4j.wml.Tbl;
import org.docx4j.wml.UnderlineEnumeration;
public class OpenMainDocumentAndTraverse extends AbstractSample
{
public static void main(String[] args) throws Exception
{
try
{
getInputFilePath(args);
}
catch (IllegalArgumentException e)
{
inputfilepath = System.getProperty("user.dir")
+ "/sample-docs/sample-docx.xml";
}
WordprocessingMLPackage wordMLPackage = WordprocessingMLPackage
.load(new java.io.File(inputfilepath));
final MainDocumentPart documentPart = wordMLPackage.getMainDocumentPart();
org.docx4j.wml.Document wmlDocumentEl = (org.docx4j.wml.Document) documentPart
.getJaxbElement();
Body body = wmlDocumentEl.getBody();
new TraversalUtil(body,
new Callback()
{
String indent = "";
org.docx4j.wml.ObjectFactory factory = new org.docx4j.wml.ObjectFactory();
org.docx4j.wml.R tmpR = factory.createR();
public List<Object> apply(Object o)
{
String text = "";
if (o instanceof org.docx4j.wml.Text)
{
org.docx4j.wml.Text t = (org.docx4j.wml.Text) o;
text = t.getValue();
if(text.equals("ssss"))
{
org.docx4j.wml.R r = (org.docx4j.wml.R) t.getParent();
org.docx4j.wml.P parent = (org.docx4j.wml.P) r.getParent();
int index = documentPart.getContent().indexOf(parent);
documentPart.getContent().remove(parent);
}
}
if (o instanceof org.docx4j.wml.R)
{
tmpR = (org.docx4j.wml.R) o;
}
return null;
}
public boolean shouldTraverse(Object o)
{
return true;
}
// Depth first
public void walkJAXBElements(Object parent)
{
indent += " ";
List children = getChildren(parent);
if (children != null)
{
for (Object o : children)
{
o = XmlUtils.unwrap(o);
this.apply(o);
if (this.shouldTraverse(o))
{
walkJAXBElements(o);
}
}
}
indent = indent.substring(0, indent.length() - 4);
}
public List<Object> getChildren(Object o)
{
return TraversalUtil.getChildrenImpl(o);
}
}
);
wordMLPackage.save(new File("c:\\workspace\\test_out.docx"));
}
}
the result of running is "Exception in thread "main" java.lang.ClassCastException: javax.xml.bind.JAXBElement".
attachment is example word document!
thanks in advance!
tosswang