如果在SAX中设置setNamespaceAware(true),如何获取"xmlns:XXX"属性?

Dee*_*Two 5 java xml namespaces saxparser

这是我的代码:

path = wsdlPath;
SAXParserFactory saxfac = SAXParserFactory.newInstance();
saxfac.setNamespaceAware(true);
saxfac.setXIncludeAware(true);
saxfac.setValidating(false);
SAXParser saxParser = saxfac.newSAXParser();
saxParser.parse(wsdlPath, this);
Run Code Online (Sandbox Code Playgroud)

设置后setNamespaceAware=true,我无法获取方法xmlns:XXX参数attributes中的属性public void startElement(String uri, String localName, String qName, Attributes attributes).

对于以下节点:

<definitions name="Service1"
    targetNamespace="http://www.test.com/service"
    xmlns="http://schemas.xmlsoap.org/wsdl/"
    xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/"
    xmlns:mime="http://schemas.xmlsoap.org/wsdl/mime/"
    xmlns:http="http://schemas.xmlsoap.org/wsdl/http/"
    xmlns:tns="http://www.test.com/">
Run Code Online (Sandbox Code Playgroud)

我得到nametargetNamespace归因于.xmlns,xmlns:wsdl,xmlns:mime,xmlns:http并且xmlns:tns是在attributes参数.但他们无法访问.

有没有办法使用setNamespaceAware=true并获取节点的所有属性?

Joa*_*uer 8

当您的XML解析器知道XML Namespace时,您不应该需要访问这些属性,因为它们只定义XML中使用的命名空间的短名称.

在这种情况下,您总是使用其全名来引用名称空间(例如http://schemas.xmlsoap.org/wsdl/),并且可以忽略它们在XML中的别名的短名称(例如wsdl).

SAX不提供这些值的事实记录在Attributes类中:

xmlns*除非将该http://xml.org/sax/features/namespace-prefixes功能设置为true(false默认情况下),否则它将不包含用作命名空间声明()的属性.

所以使用saxfac.setFeature("http://xml.org/sax/features/namespace-prefixes", true)应该可以帮助你实现这些价值观.