Getting XML Node text value with Java DOM

后端 未结 4 1245
滥情空心
滥情空心 2020-11-27 06:16

I can\'t fetch text value with Node.getNodeValue(), Node.getFirstChild().getNodeValue() or with Node.getTextContent().

My XML

4条回答
  •  野趣味
    野趣味 (楼主)
    2020-11-27 06:52

    If you are open to vtd-xml, which excels at both performance and memory efficiency, below is the code to do what you are looking for...in both XPath and manual navigation... the overall code is much concise and easier to understand ...

    import com.ximpleware.*;
    public class queryText {
        public static void main(String[] s) throws VTDException{
            VTDGen vg = new VTDGen();
            if (!vg.parseFile("input.xml", true))
                return;
            VTDNav vn = vg.getNav();
            AutoPilot ap = new AutoPilot(vn);
            // first manually navigate
            if(vn.toElement(VTDNav.FC,"tag")){
                int i= vn.getText();
                if (i!=-1){
                    System.out.println("text ===>"+vn.toString(i));
                }
                if (vn.toElement(VTDNav.NS,"tag")){
                    i=vn.getText();
                    System.out.println("text ===>"+vn.toString(i));
                }
            }
    
            // second version use XPath
            ap.selectXPath("/add/tag/text()");
            int i=0;
            while((i=ap.evalXPath())!= -1){
                System.out.println("text node ====>"+vn.toString(i));
            }
        }
    }
    

提交回复
热议问题