我有一个需要导航的XML文件,它类似于(完整的XML是here):
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<md:EntitiesDescriptor xmlns:md="urn:oasis:names:tc:SAML:2.0:metadata">
<md:EntityDescriptor xmlns:saml2="urn:oasis:names:tc:SAML:2.0:assertion" xmlns:saml2p="urn:oasis:names:tc:SAML:2.0:protocol" xmlns:xsi="http://www.w3.org/2001/XMLSchemainstance" ID="_id-83bbfdd3-e4c4-42cf-a024-e4733569a4ae" entityID="https://id.eht.eu">
<md:Organization>
<md:OrganizationName xml:lang="it">EtnaHitech</md:OrganizationName>
<md:OrganizationName xml:lang="en">EtnaHitech</md:OrganizationName>
<md:OrganizationDisplayName xml:lang="it">EHT</md:OrganizationDisplayName>
<md:OrganizationDisplayName xml:lang="en">EHT</md:OrganizationDisplayName>
</md:Organization>
</md:EntityDescriptor>
<md:EntityDescriptor xmlns:saml2="urn:oasis:names:tc:SAML:2.0:assertion" xmlns:xs="http://www.w3.org/2001/XMLSchemainstance" ID="_gh3s48d19e23e85be40k4ab5ey331e7k4f04f73fb5" entityID="https://id.lepida.it/idp/shibboleth">
<md:Organization>
<md:OrganizationName xml:lang="it">Lepida</md:OrganizationName>
<md:OrganizationDisplayName xml:lang="it">Lepida</md:OrganizationDisplayName>
</md:Organization>
</md:EntityDescriptor>
</md:EntitiesDescriptor>
假设我想要获取具有特定值的属性entityID
的 node /元素md:EntityDescriptor
,例如entityID="https://id.eht.eu"
我try 在Java中使用XPath,以下是我的代码:
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.parse("C:/outputTest/input.xml");
XPathFactory xPathfactory = XPathFactory.newInstance();
XPath xpath = xPathfactory.newXPath();
XPathExpression expr = xpath.compile("//md:EntityDescriptor[@entityID='https://id.eht.eu']");
NodeList nl = (NodeList) expr.evaluate(doc, XPathConstants.NODESET);
当我试着对结果骑自行车的时候:
if (nl != null && nl.getLength() != 0) {
for (int i = 0; i < nl.getLength(); i++) {
System.out.println(nl.item(i).getNodeValue());
}
}
我的NodeList
总是空的.我没法让这玩意儿动起来.我希望它至少在我的NodeList
中获得指定的 node ,然后我将try 将其从文档中完全删除.通常,我需要创建一些东西来获取具有指定值entityID
的任何 node md:EntityDescriptor
,然后将其从文档中删除.