java xml id,Java XML DOM:id属性如何?

The javadoc for the Document class has the following note under getElementById.

Note: Attributes with the name "ID" or "id" are not of type ID unless so defined

So, I read an XHTML doc into the DOM (using Xerces 2.9.1).

The doc has a plain old

in it.

I call getElementById("fribble"), and it returns null.

I use XPath to get "//*[id='fribble']", and all is well.

So, the question is, what causes the DocumentBuilder to actually mark ID attributes as 'so defined?'

解决方案

For the getElementById() call to work, the Document has to know the types of its nodes, and the target node must be of the XML ID type for the method to find it. It knows about the types of its elements via an associated schema. If the schema is not set, or does not declare the id attribute to be of the XML ID type, getElementById() will never find it.

My guess is that your document doesn't know the p element's id attribute is of the XML ID type (is it?). You can navigate to the node in the DOM using getChildNodes() and other DOM-traversal functions, and try calling Attr.isId() on the id attribute to tell for sure.

From the getElementById javadoc:

The DOM implementation is expected to

use the attribute Attr.isId to

determine if an attribute is of type

ID.

Note: Attributes with the name "ID" or

"id" are not of type ID unless so

defined.

If you are using a DocumentBuilder to parse your XML into a DOM, be sure to call setSchema(schema) on the DocumentBuilderFactory before calling newDocumentBuilder(), to ensure that the builder you get from the factory is aware of element types.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值