使用VTD-XML获取属性名称和值

时间:2016-11-21 06:04:18

标签: java vtd-xml

我正在编写一个代码来读取XML String中的属性名称和值,但是我的节点表示为例如hi:collection所以编译器将其作为URL并抛出错误找不到前缀的URL :喜

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

import java.net.HttpURLConnection;
import java.net.URL;


   import javax.xml.parsers.ParserConfigurationException;
   import javax.xml.xpath.XPathExpressionException;

     import com.ximpleware.*;

    import org.xml.sax.SAXException;
public class A20 {

public static void main(String[] args) throws IOException, XPathExpressionException, ParserConfigurationException, SAXException, XPathParseException, XPathEvalException, NavException{

    URL a=new URL("URL");
    HttpURLConnection b=(HttpURLConnection) a.openConnection();
    b.setRequestMethod("GET");
    b.setRequestProperty("Accept", "application/xml");
BufferedReader c=new BufferedReader(new InputStreamReader(b.getInputStream()));
StringBuilder sb=new StringBuilder();

String out,out1 = null;
while((out=c.readLine())!=null)
 {sb.append(out);
 out1=sb.toString();
  System.out.println( out1);   }
  c.close();
  b.disconnect();

   byte[] bytes = out1.getBytes("UTF-8");
   VTDGen vg = new VTDGen();
   vg.setDoc(bytes);
VTDNav vn = vg.getNav();
AutoPilot ap =  new AutoPilot(vn);

ap.selectXPath("//hi:collection/@name");// I am getting error here 
int i=0;
while( (i=ap.evalXPath())!=-1){
     System.out.println(" item name is ===>"+vn.toString(i+1)); 
}
}

}

1 个答案:

答案 0 :(得分:0)

您收到该错误的原因是因为您尚未声明前缀(在本例中为hi)与其相应的URL之间的绑定,这是必需且必不可少的。

修复方法是在selectXPath之前调用AutoPilot的declareNamespaceURL()方法。

另一个建议:您可以使用VTDGen的parseHTTPURL方法直接从URL地址读取...从而节省您处理URL的工作......