java xml element,java xml将节点转换为Element

I know this was asked many times but I still cannot get it to work. I convert xml string to Document object and then parse it. Here is the code:

import javax.xml.parsers.DocumentBuilder;

import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.*;

DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();

DocumentBuilder builder;

try

{

builder = factory.newDocumentBuilder();

Document document = builder.parse( new InputSource( new StringReader( result ) ) );

Node head = document.getFirstChild();

if(head != null)

{

NodeList airportList = head.getChildNodes();

for(int i=0; i

Node n = airportList.item(i);

Element airportElem = (Element)n;

}

}

catch (Exception e) {

e.printStackTrace();

}

When I cast the Node object n to Element I get an exception java.lang.ClassCastException: org.apache.harmony.xml.dom.TextImpl cannot be cast to org.w3c.dom.Element. When I check the node type of the Node object it says Node.TEXT_NODE. I believe it should be Node.ELEMENT_NODE. Am I right?

So how do I convert Node to Element, so I can do something like element.getAttribute("attrName").

Here is my XML:

Abu Dhabi

AUH

Amsterdam

AMS

Antalya

AYT

Bangkok

BKK

Thanks in advance!

解决方案

When I cast the Node object n to Element I get an exception java.lang.ClassCastException: org.apache.harmony.xml.dom.TextImpl cannot be cast to org.w3c.dom.Element. When I check the node type of the Node object it says Node.TEXT_NODE. I believe it should be Node.ELEMENT_NODE. Am I right?

Probably not, the parser is probably right. It means that some of the nodes in what you're parsing are text nodes. For example:

bar

In the above, we have a foo element containing a text node. (The text node contains the text "bar".)

Similarly, consider:

baz

If your XML document literally looks like the above, it contains a root element foo with these child nodes (in order):

A text node with some whitespace in it

A bar element

A text node with some more whitespace in it

Note that the bar element is not the first child of foo. If it looked like this:

baz

then the bar element would be the first child of foo.

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值