gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-03 03:12:14 25 4
gpt4 key购买 nike

我有以下 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com