Java 使用JDOM获取XML元素
我有一个如下所示的XML文件Java 使用JDOM获取XML元素,java,xml,saml,jdom,Java,Xml,Saml,Jdom,我有一个如下所示的XML文件 <samlp:AuthnRequest xmlns:samlp="urn:oasis:names:tc:SAML:2.0:protocol" Destination="https://hostname.example.com:4444/fed/idp/samlv20" ID="id-OPIfhD3il2eK816THPlj2Nk38KM-"
<samlp:AuthnRequest xmlns:samlp="urn:oasis:names:tc:SAML:2.0:protocol"
Destination="https://hostname.example.com:4444/fed/idp/samlv20"
ID="id-OPIfhD3il2eK816THPlj2Nk38KM-"
IssueInstant="2014-09-02T14:36:02Z"
ProtocolBinding="urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST"
Version="2.0"
>
<saml:Issuer xmlns:saml="urn:oasis:names:tc:SAML:2.0:assertion"
Format="urn:oasis:names:tc:SAML:2.0:nameid-format:entity"
>https://federation.example.com/sp</saml:Issuer>
<samlp:NameIDPolicy AllowCreate="true"
Format="urn:oasis:names:tc:SAML:1.1:nameid-format:unspecified"
/>
<samlp:RequestedAuthnContext Comparison="exact">
<saml:AuthnContextClassRef xmlns:saml="urn:oasis:names:tc:SAML:2.0:assertion">urn:oasis:names:tc:SAML:2.0:ac:classes:PasswordProtectedTransport</saml:AuthnContextClassRef>
</samlp:RequestedAuthnContext>
</samlp:AuthnRequest>
由于以下几个原因,上面的代码将不起作用。首先,samlRequestAttribute[2]=…
行将抛出ArrayIndexOutOfBounds异常,因为没有索引值2。您应该使用索引1
您没有指明要将值存储在何处https://federation.example.com/sp
,但我假设您希望它出现在返回数组的某个位置(可能在索引1?)
检索它的方法是正确地为XML使用名称空间
考虑以下几点:
private String[] getRequestAttributes(String xmlString) throws SamlException {
Document doc = Util.createJdomDoc(xmlString);
if (doc != null) {
Namespace saml = Namespace.get("urn:oasis:names:tc:SAML:2.0:assertion");
String[] samlRequestAttributes = new String[3];
Element root = doc.getRootElement();
samlRequestAttributes[0] = root.getAttributeValue("IssueInstant");
samlRequestAttributes[1] = root.getAttributeValue("ProtocolBinding");
samlRequestAttributes[2] = root.getChild("Issuer", saml).getText();
return samlRequestAttributes;
}
}
注意您需要如何标识子元素的名称空间,并在getChild调用中使用正确的名称空间从根文档中检索它
private String[] getRequestAttributes(String xmlString) throws SamlException {
Document doc = Util.createJdomDoc(xmlString);
if (doc != null) {
String[] samlRequestAttributes = new String[2];
samlRequestAttributes[0] = doc.getRootElement().getAttributeValue(
"IssueInstant");
samlRequestAttributes[2] = doc.getRootElement().getAttributeValue(
"ProtocolBinding");
return samlRequestAttributes;
}
}
private String[] getRequestAttributes(String xmlString) throws SamlException {
Document doc = Util.createJdomDoc(xmlString);
if (doc != null) {
Namespace saml = Namespace.get("urn:oasis:names:tc:SAML:2.0:assertion");
String[] samlRequestAttributes = new String[3];
Element root = doc.getRootElement();
samlRequestAttributes[0] = root.getAttributeValue("IssueInstant");
samlRequestAttributes[1] = root.getAttributeValue("ProtocolBinding");
samlRequestAttributes[2] = root.getChild("Issuer", saml).getText();
return samlRequestAttributes;
}
}