我正在从字符串xml生成Document。
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)));
我想对xml请求进行数字签名,我使用的是javax.xml库。为了生成引用,我需要传递我需要数字签名的元素的uri。我用来生成引用的代码是:
Reference ref = fac.newReference(id, fac.newDigestMethod(DigestMethod.SHA256, null), transformList, null, null);
在上面的函数中,我得到了一个错误解析器。ResourceResolverException:无法解析ID为的元素。当我进入函数newReference时。其调用
Element e = doc.getElementById(idValue);
doc.getElementById(idValue(正在返回null。我写了一个测试用例来测试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);
这也显示为null。知道我在这里做错了什么吗?
将xmlString解析为Document的方式是正确的。该文档包含元素。但是String中的属性"id"不是Document元素的ID
(不区分大小写(。Document.getElementById(String elementId)
的医生说:
返回具有给定值的ID属性的元素。如果不存在这样的元素,则返回null。。。DOM实现应使用属性Attr.isId来确定属性是否为ID类型。注意:除非定义了名称为"ID"或"ID"的属性,否则它们不是ID类型
应该有另一个DTD文件来定义该xml中哪个属性是ID
。这里是一个示例,在该示例中,ID
是artistID
。
所以你到达一个元素的正确方式是这样的:
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
在您的情况下,"id"不是一个特殊的元素,它只是一个包含信息的简单属性。