I am generating Document from string xml.
javax.xml.parsers.DocumentBuilderFactory dbf =javax.xml.parsers.DocumentBuilderFactory.newInstance();
dbf.setNamespaceAware(true);
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(new InputSource(new StringReader(xml)));
I want to digitally sign xml request, I am using javax.xml library. Inorder to generate references, I need to pass uri of element that i neeed to digitally sign. Code i am using to generate reference is this :
Reference ref = fac.newReference(id, fac.newDigestMethod(DigestMethod.SHA256, null), transformList, null, null);
Inside above function, I am getting error resolver.ResourceResolverException: Cannot resolve element with ID . When i went inside the function newReference . Its calling
Element e = doc.getElementById(idValue);
doc.getElementById(idValue) is returning null. I wrote one test case to test getElementById
String xmlString = "<?xml version=\"1.0\" encoding=\"iso-8859-1\"?><request> <myxml id=\"122\" ></myxml></request>";
String cleanXml = xmlString.replaceAll("\\r", "").replaceAll("\\n", "");
Document doc = convertXmlStringToDoc(cleanXml);
Element e = doc.getElementById("122");
System.out.println(e);
this is also showing null. Any idea, what i am doing wrong here ?
The way you parse xmlString to Document is right. The document contains the elements. But the attribute "id" in your String is not ID
(doesn't matter case sensitive) of Document element. The doc of Document.getElementById(String elementId)
said:
Returns the Element that has an ID attribute with the given value. If no such element exists, this returns null . ... The DOM implementation is expected to use the attribute Attr.isId to determine if an attribute is of type ID. Note: Attributes with the name "ID" or "id" are not of type ID unless so defined.
There should be another DTD file to define which attribute is ID
in this xml. Here is an example, in that example, the ID
is artistID
.
So the right way you reach an element is like this:
Element element = doc.getElementById("122"); // null
//System.out.println(element.getNodeValue());
NodeList e = doc.getElementsByTagName("myxml");
NamedNodeMap namedNodeMap = e.item(0).getAttributes();
String value = namedNodeMap.getNamedItem("id").getNodeValue();
System.out.println(value); // 122
In your case, "id" is not a special element, it's just a simple attribute to contain information.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.