<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<EmployeeList xmlns="http://annmgc00523.blogspot.com/"
xmlns:tr="http://annmgc00523.blogspot.com/trainee"> // tr ở đây là kí hiệu tiền tố của namespace.
<tr:Employee>
<tr:Name>nguyen van0</tr:Name>
<Address>address1</Address>
</tr:Employee>
<tr:Employee>
<Name>nguyen van1</Name>
<Address>address1</Address>
</tr:Employee>
<tr:Employee>
<Name>nguyen van3</Name>
<Address>address3</Address>
</tr:Employee>
<tr:Employee>
<Name>nguyen van4</Name>
<Address>address4</Address>
</tr:Employee>
<tr:Employee>
<Name>nguyen van5</Name>
<Address>address5</Address>
</tr:Employee>
</EmployeeList>
Khai báo ở hàm main:
public static void main(String[] args) {
try {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setNamespaceAware(true);
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.parse(new File("D:\\NetBean\\Module9\\src\\Employee.xml"));
NamespaceContext ctx = new NamespaceContext() {
@Override
public String getNamespaceURI(String prefix) {
String uri = "";
if (prefix.equals("tr")) {
uri = "http://annmgc00523.blogspot.com/trainee";
}
return uri;
}
@Override
public String getPrefix(String string) {
return null;
}
@Override
public Iterator getPrefixes(String string) {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
};
String xpathLink = "//tr:Employee";
XPathFactory xpathFactory = XPathFactory.newInstance();
XPath xp = xpathFactory.newXPath();
xp.setNamespaceContext(ctx);
NodeList nl = (NodeList) xp.evaluate(xpathLink, doc, XPathConstants.NODESET);
System.out.println("Số kết quả: " + nl.getLength());
for (int i = 0; i < nl.getLength(); i++) {
System.out.println(nl.item(i).getTextContent());
}
} catch (XPathExpressionException ex) {
Logger.getLogger(Module9.class.getName()).log(Level.SEVERE, null, ex);
} catch (SAXException | IOException | ParserConfigurationException ex) {
Logger.getLogger(Module9.class.getName()).log(Level.SEVERE, null, ex);
}
}
Nhận xét:
XPath tương đối phức tạp trong mảng khai báo và sử dụng,
Phải viết nhiều code
Không có nhận xét nào:
Đăng nhận xét