1

I have an xml document like this:

<?xml version="1.0" encoding="UTF-8"?>
<body>
<request>
<location>
  <address />
</location>
</request> 
</body>

My goal is to insert the value "My Address" into this document in order to have:

<?xml version="1.0" encoding="UTF-8"?>
<body>
<request>
<location>
  <address>
    My Address
  </address>
</location>
</request> 
</body>

I have to reach this goal in a java class that must create this document reading it from an XML file (ok) and i have an XPath expression (/request/location/address) that indicates me where to put my text ("My address"). How to implement a Java class that allows me, starting from xml and XPath string, to insert a text into a node? This java class must be universal, not bound to a particular XML structure (this is the reason why I use an XPath expression instead of getting the XMl structure into the class). I hope my question is clear.

2
  • The XPath /request/location/address would not select anything at all in the document as your root element is body and not request. As for the Java code and XPath, see docs.oracle.com/javase/7/docs/api/javax/xml/xpath/… on how to select a node. Commented Mar 9, 2016 at 10:08
  • Yes, i made mistake in writing XPath, thanks. I don't know how to use the correct XPath expression in order to insert the text in that position. Commented Mar 10, 2016 at 9:11

1 Answer 1

1

Here is the code to do this vtd-xml....

import com.ximpleware.*;

public class insertTextNode {
    public static void main(String[] s) throws VTDException, Exception {
        VTDGen vg = new VTDGen();
        AutoPilot ap = new AutoPilot();
        XMLModifier xm = new XMLModifier();
        if (vg.parseFile("input.xml", true)) {
            VTDNav vn = vg.getNav();
            ap.bind(vn);
            xm.bind(vn);
            ap.selectXPath("/body/request/location/address");
            int i=0;
            while((i=ap.evalXPath())!=-1){
                xm.insertAfterHead("myAddress");
            }
            xm.output("output.xml");
        }
    }
}
Sign up to request clarification or add additional context in comments.

2 Comments

I also solved this problem by myself with JDOM2, but this is a very helpful method, too. When i'll time to write my way i'll update this post with my personal answer. Thank you anyway, vtd.xml-author.
JDOM Is among the slowest and most resource wasteful api out there, here is the proof sdiwc.us/digitlib/journal_paper.php?paper=00000582.pdf

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.