Monday, April 4, 2011

Xpath with prefix

XML file:

<ns:authenticateResponse xmlns:ns='http://webservices.surfbi.fcs.com'>
   <ns:return xmlns:ax27='http://exception.surfbi.fcs.com/xsd' xmlns:ax210='http://dto.surfbi.fcs.com/xsd' type='com.fcs.surfbi.dto.UserDTO'>
      <ax210:first_name>SurfBI</ax210:first_name>
    </ns:return>
</ns:authenticateResponse>



java程式碼, 在使用Xpath時要用xpath.setNamespaceContext()設定Namespace。

DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
domFactory.setNamespaceAware(true); 
DocumentBuilder builder = domFactory.newDocumentBuilder();
 
InputStream is = new ByteArrayInputStream(xmlInput.getBytes("UTF-8"));
Document doc = builder.parse(is);
            
XPathFactory factory = XPathFactory.newInstance();
XPath xpath = factory.newXPath();
xpath.setNamespaceContext(new FCSNamespaceContext());
 
String nil = xpath.evaluate("//ns:authenticateResponse/ns:return/@xsi:nil", doc);
XPathExpression expr = xpath.compile("//ns:authenticateResponse/ns:return/ax210:first_name");
Object result = expr.evaluate(doc, XPathConstants.NODESET);
NodeList nodes = (NodeList) result;
 for (int i = 0; i < nodes.getLength(); i++) {
 
  String test = nodes.item(i).getTextContent();
 }



NamespaceContext

public class FCSNamespaceContext implements NamespaceContext{
    public String getNamespaceURI(String prefix)
    {
        if (prefix.equals("ns"))
            return "http://webservices.surfbi.fcs.com";
        else if (prefix.equals("ax210"))
            return "http://dto.surfbi.fcs.com/xsd";
        else if (prefix.equals("ax27"))
            return "http://exception.surfbi.fcs.com/xsd";
        else if (prefix.equals("xsi"))
            return "http://www.w3.org/2001/XMLSchema-instance";
        else
            return XMLConstants.NULL_NS_URI;
    }
    
    public String getPrefix(String namespace)
    {
        if (namespace.equals("http://webservices.surfbi.fcs.com"))
            return "ns";
        else if (namespace.equals("http://dto.surfbi.fcs.com/xsd"))
            return "ax210";
        else if (namespace.equals("http://exception.surfbi.fcs.com/xsd"))
            return "ax27";
        else if (namespace.equals("http://www.w3.org/2001/XMLSchema-instance"))
            return "xsi";
        else
            return null;
    }
 
    public Iterator getPrefixes(String namespace)
    {
        ArrayList list = new ArrayList();
        
        if ( namespace.equals( "http://webservices.surfbi.fcs.com")) {
          list.add( "ns");
        } else if ( namespace.equals( "http://dto.surfbi.fcs.com/xsd")) 
            list.add( "ax210");
        
      
        return list.iterator();
 
    }
}

No comments:

Post a Comment