从 XML 文件获取命名空间

Get Namespaces from an XML file

提问人:jherranzm 提问时间:3/25/2021 更新时间:3/25/2021 访问量:152

问:

我有这个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 不是我要查找的值。

我做错了什么?

提前感谢您的回答。

Java XML 命名空间

评论

2赞 Parfait 3/25/2021
这有帮助吗:stackoverflow.com/q/27715183
1赞 jherranzm 3/25/2021
谢谢你@Parfait!你的帖子是我需要的。我需要使用 .getLocalName() 才能获得“fe”和“ds”。多谢!

答:

3赞 vanje 3/25/2021 #1

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

而不是

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

评论

0赞 jherranzm 3/25/2021
谢谢!它工作得很好。还有一件事:我认为getPrefix()在这两种情况下会导致获得“ds”和“fe”,但只会导致第一部分。有什么方法可以得到冒号之外的东西“:”?
0赞 jherranzm 3/25/2021
多亏了@Parfait解决了:.getLocalName() 方法是获取“ds”和“fe”所需的方法。