java - 从 Java 中的元素中检索命名空间(使用 DOM)

标签 java dom xpath

我有以下 XML 示例:

<?xml version="1.0" encoding="UTF-8"?>
<OpenSearchDescription xmlns="http://a9.com/-/spec/opensearch/1.1/"
    xmlns:custom="http://example.com/opensearchextensions/1.0/">
    <ShortName>Test</ShortName>
    <Description>Testing....</Description>
    <Url template="whatever" type="what" />
    <Query custom:color="blue" role="example" />
</OpenSearchDescription>

我关心的是 Query 元素。它有一个命名空间属性,在 java 中,您需要一个 namespaceURI 来检索值。

我的问题是:如何从根元素(在本例中为 OpenSearchDescription 元素)检索 namespace 列表?我想要可用于在 Query 上请求的属性、前缀和命名空间 URI。

谢谢。

PS:我在 Java 中使用 DOM,在 Java SE 中是标准的。如果可能的话,我愿意转向 XPath。要求是只需要使用 Java 标准 API。

最佳答案

这可能会让您入门,factory.setNamespaceAware(true) 毕竟是获取命名空间数据的关键。

public static void main(String[] args) throws ParserConfigurationException, SAXException,
        IOException
{
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    factory.setNamespaceAware(true);
    DocumentBuilder builder = factory.newDocumentBuilder();
    Document doc = builder.parse(new File(args[0]));
    Element root = doc.getDocumentElement();
    //prints root name space
    printAttributesInfo((Node) root);

    NodeList childNodes = root.getChildNodes();
    for (int i = 0; i < childNodes.getLength(); i++)
    {
        printAttributesInfo(childNodes.item(i));
    }
}

public static void printAttributesInfo(Node root)
{
    NamedNodeMap attributes = root.getAttributes();
    if (attributes != null)
    {
        for (int i = 0; i < attributes.getLength(); i++)
        {
            Node node = attributes.item(i);
            if (node.getNodeType() == Node.ATTRIBUTE_NODE)
            {
                String name = node.getNodeName();
                System.out.println(name + " " + node.getNamespaceURI());
            }
        }
    }
}

关于java - 从 Java 中的元素中检索命名空间(使用 DOM),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8939468/

相关文章:

java - 如何将字符串拆分为单词和非单词

javascript - 需要 getElementsByTagName 函数

javascript - 为什么嵌套元素是由last-of-type选择的?

java - Xpath 在节点下插入节点序列 - Java

java - 如何通过xpath查找以空格和值结尾的元素

java - jlabel 文本在打印时被截断

java - 如何在自定义反序列化器Gson中小写JsonElement值?

java - 将字符串数组元素与文字字符串进行比较

javascript - 在浏览器中,如何检测与按钮交互触发了什么事件?

python - Xpath 使用 Scrapy 获取下一个兄弟标签中的信息