Add node using JXPATH
-
14-06-2021 - |
Domanda
I am using jxpath to print all nodes and add a child node to the feature tag in this xml
<extracts>
<extract>
<id>1</id>
<features>
<feature>1</feature>
<feature>2</feature>
</extract>
</extracts>
This is what my code looks like (the part that works at least - it prints some information):
import org.apache.commons.jxpath.ri.model.*;
import org.apache.commons.jxpath.JXPathContext;
import org.apache.commons.jxpath.Pointer;
try {
DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
ByteArrayInputStream bais = new ByteArrayInputStream(getBytesFromFile(file));
Document doc = builder.parse(bais);
JXPathContext jxpathCtx = JXPathContext.newContext(doc.getDocumentElement());
jxpathCtx.setLenient(true);
The first part of my requirement - which is to print these nodes -- is trivial:
for (Iterator iter2 = jxpathCtx.iterate("/extract/*"); iter2.hasNext();)
{
System.out.println("\n Value is : " + iter2.next().toString() +"\n");
}
The second part of my requirement is what gets to me
I need to add a new entry --a new < feature >3< /feature > node UNDER the existing <features>
tag under < extract >
programatically
It could be something along the lines of isolating that node - and then adding a child to it - i just dont know how to go about it :
org.apache.commons.configuration.HierarchicalConfiguration.NodeNode node = (Node)jxpathCtx.selectNodes("/extract/lastruns/lastrun");
for (Element node : nodes)
{
}
Any ideas/help would be appreciated
Soluzione
This XSLT transformation:
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output omit-xml-declaration="yes" indent="yes"/>
<xsl:strip-space elements="*"/>
<xsl:template match="node()|@*" name="identity">
<xsl:copy>
<xsl:apply-templates select="node()|@*"/>
</xsl:copy>
</xsl:template>
<xsl:template match="feature[last()]">
<xsl:call-template name="identity"/>
<feature>3</feature>
</xsl:template>
</xsl:stylesheet>
when applied on the provided XML document (corrected to be made well-formed):
<extracts>
<extract>
<id>1</id>
<features>
<feature>1</feature>
<feature>2</feature>
</features>
</extract>
</extracts>
produces the wanted, correct result:
<extracts>
<extract>
<id>1</id>
<features>
<feature>1</feature>
<feature>2</feature>
<feature>3</feature>
</features>
</extract>
</extracts>
Explanation:
Proper use and overriding of the identity rule.