[jdom-interest] Modifying the Tag Content
Laurent Bihanic
laurent.bihanic at atosorigin.com
Tue Aug 19 08:03:08 PDT 2003
sundardba at vsnl.net wrote:
> I have problem in XML. I have the XML content like this.
>
> <abstract>
> <P>The XML 1.0 specification specifically reserves the colon character<P>
> for use with XML Namespaces.
> <P>No other use is compliant with XML 1.0. Therefore JDOM <P>
> </abstract>
>
> I just want ot add <P> tag like this
> <P> for use with XML Namespaces</P>
>
> Is it possible to do this. This may appear in any number of places.
With JDOM beta9, using XPath to select the elements to modify, you could try
something like :
Filter filter = new ContentFilter(ContentFilter.TEXT | ContentFilter.ELEMENT);
XPath xp = XPath.newInstance("//P/..[text()!='']");
for (Iterator i=xp.selectNodes(doc).iterator(); i.hasNext(); )
{
Element e = (Element)(i.next());
List l = e.getContent(filter);
for (int j=0, max=l.size(); j<max; j++)
{
Object child = l.get(j);
if (child instanceof Text)
{
String text = ((Text)child).getText();
String content = text.trim();
if (content.length() != 0)
{
Element p = new Element("P");
p.setText(content);
int pos = text.indexOf(content);
l.set(j, new Text(text.substring(pos + content.length())));
l.add(j, p);
l.add(j, new Text(text.substring(0, pos)));
}
}
}
}
It will produce the following document :
<?xml version="1.0" encoding="UTF-8"?>
<abstract>
<P>The XML 1.0 specification specifically reserves the colon character</P>
<P>for use with XML Namespaces.</P>
<P>No other use is compliant with XML 1.0. Therefore JDOM </P>
</abstract>
Laurent
More information about the jdom-interest
mailing list