如果在SAX中设置setNamespaceAware(true),如何获取“xmlns:XXX”属性?
这是我的代码:
path = wsdlPath; SAXParserFactory saxfac = SAXParserFactory.newInstance(); saxfac.setNamespaceAware(true); saxfac.setXIncludeAware(true); saxfac.setValidating(false); SAXParser saxParser = saxfac.newSAXParser(); saxParser.parse(wsdlPath, this);
在设置setNamespaceAware=true
,我无法在方法public void startElement(String uri, String localName, String qName, Attributes attributes)
参数attributes
中获取xmlns:XXX
属性。
对于以下节点:
我只获取name
和targetNamespace
属性。 xmlns
, xmlns:wsdl
, xmlns:mime
, xmlns:http
和xmlns:tns
在attributes
参数中。 但他们无法访问。
有没有办法使用setNamespaceAware=true
并获取节点的所有属性?
当您的XML解析器知道XML Namespace时,您不应该需要访问这些属性,因为它们只定义XML中使用的命名空间的短名称。
在这种情况下,您总是使用其全名引用名称空间(例如http://schemas.xmlsoap.org/wsdl/
),并且可以忽略它们在XML中的别名短名称(例如wsdl
)。
SAX不提供这些值的事实记录在Attributes
类中 :
除非
http://xml.org/sax/features/namespace-prefixes
function设置为true
(默认情况下为false
),否则它将不包含用作命名空间声明(xmlns*
)的属性。
因此,使用saxfac.setFeature("http://xml.org/sax/features/namespace-prefixes", true)
可以帮助您获得这些值。
获取命名空间声明的标准方法来自startPrefixMapping事件: