从 XML 文件获取命名空间

Get Namespaces from an XML file

我有这个 XML 文件,我需要知道命名空间的 URI。

<?xml version="1.0" encoding="utf-8"?>
<fe:Facturae 
    xmlns:ds="http://www.w3.org/2000/09/xmldsig#" 
    xmlns:fe="http://www.facturae.es/Facturae/2014/v3.2.1/Facturae" >
    <FileHeader>
    </FileHeader>
</fe:Facturae>

我正在使用 Java (jdk16) 和这段代码来获取它们:

        try {
            
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            factory.setNamespaceAware(true);
            DocumentBuilder builder = factory.newDocumentBuilder();
            Document doc1 = builder.parse(new File(FACTURA_MODELO_XML));
            Element element = doc1.getDocumentElement();
            
            logger.info("element         : {}", element.getNodeName());
            
            NamedNodeMap attributes = element.getAttributes();
            
            if (attributes != null){
                for (int i = 0; i < attributes.getLength(); i++){
                    Attr attribute = (Attr)attributes.item(i);
                    logger.info("attribute.Name         : {}", attribute.getNodeName());
                    logger.info("attribute.NamespaceURI : {}", attribute.getNamespaceURI());
                    logger.info("attribute.Prefix       : {}", attribute.getPrefix());
          
                }
            }
         } catch (Exception ex){
            // print exception
         }

但是 运行 这段代码给我带来了以下结果:


[main] INFO attribute.Name         : xmlns:ds
[main] INFO attribute.NamespaceURI : http://www.w3.org/2000/xmlns/
[main] INFO attribute.Prefix       : xmlns
[main] INFO attribute.Name         : xmlns:fe
[main] INFO attribute.NamespaceURI : http://www.w3.org/2000/xmlns/
[main] INFO attribute.Prefix       : xmlns

属性名称正确,但 NamespaceURI 和 Prefix 不是我要查找的值。

我做错了什么?

提前感谢您的回答。

您不需要属性的命名空间,您需要属性值。

而不是

logger.info("attribute.NamespaceURI : {}", attribute.getNamespaceURI());

你应该使用

logger.info("attribute.Value : {}", attribute.getValue());

则输出为:

element         : {}fe:Facturae
attribute.Name         : {}xmlns:ds
attribute.Value        : {}http://www.w3.org/2000/09/xmldsig#
attribute.Prefix       : {}xmlns
attribute.Name         : {}xmlns:fe
attribute.Value        : {}http://www.facturae.es/Facturae/2014/v3.2.1/Facturae
attribute.Prefix       : {}xmlns