java 中的 xml 文档的 getElementById return 为空

getElementById return null for xml document in java

我正在从字符串 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)));

我想对 xml 请求进行数字签名,我正在使用 javax.xml 库。为了生成引用,我需要传递我需要进行数字签名的元素的 uri。我用来生成参考的代码是这样的:

Reference ref = fac.newReference(id, fac.newDigestMethod(DigestMethod.SHA256, null), transformList, null, null);

在上述函数中,出现错误 resolver.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);

这也显示为空。知道吗,我在这里做错了什么?

您将 xmlString 解析为 Document 的方式是正确的。该文档包含元素。但是 String 中的属性 "id" 不是 Document 元素的 ID(不区分大小写)。 Document.getElementById(String elementId)doc表示:

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.

应该有另一个DTD文件来定义这个xml中哪个属性是IDHere 是一个示例,在该示例中,IDartistID

所以到达元素的正确方式是这样的:

        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" 不是特殊元素,它只是一个包含信息的简单属性。